evaluate the riemann in python

To evaluate a Riemann sum in Python, you can use the following code:

main.py
def riemann_sum(f, a, b, n, method='left'):
    """
    Calculate the Riemann sum of f(x) over the interval [a,b] using n subintervals
    :param f: function to integrate
    :param a: left endpoint of integration interval
    :param b: right endpoint of integration interval
    :param n: number of subintervals in Riemann sum
    :param method: method to use for evaluating Riemann sum (left, right, or midpoint)
    :return: value of Riemann sum
    """

    dx = (b - a) / n  # calculate width of subintervals
    x_vals = [a + i * dx for i in range(n+1)]  # calculate x values of subinterval endpoints

    if method == 'left':
        # evaluate f at left endpoint of each subinterval
        eval_points = x_vals[:-1]
    elif method == 'right':
        # evaluate f at right endpoint of each subinterval
        eval_points = x_vals[1:]
    elif method == 'midpoint':
        # evaluate f at midpoint of each subinterval
        eval_points = [(x_vals[i] + x_vals[i+1]) / 2 for i in range(n)]
    else:
        raise ValueError("Invalid Riemann sum method; choose 'left', 'right', or 'midpoint'.")

    # evaluate f at each evaluation point and calculate Riemann sum
    return sum([f(x) * dx for x in eval_points])
1224 chars
29 lines

You can then use this function to calculate the Riemann sum of any function over any interval. For example, to calculate the Riemann sum of f(x) = x^2 over the interval [0, 1] using n = 100 subintervals and the left Riemann sum method, you would call the function like this:

main.py
f = lambda x: x**2
a = 0
b = 1
n = 100
riemann_sum(f, a, b, n, method='left')
78 chars
6 lines

This would return the value of the left Riemann sum of f(x) = x^2 over [0, 1] using n = 100 subintervals. You can change the value of method to 'right' or 'midpoint' to use a different Riemann sum method.

gistlibby LogSnag