Calculating Riemann Sums on Python w/ Numpy

Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
4 replies · 6K views
ver_mathstats
Messages
258
Reaction score
21
Code:
import numpy as np

def num_int(f,a,b,n):
    dx=(b-a)/n
    x=np.arange(a,b,step=dx)
    y=f(x)
    return y.sum()*dx

def rational_func(x):
    return 1/(1+x**2)

print(num_int(rational_func,2,5,10))

Here is my code for the left endpoint, I know this code works because I compared it to an actual calculator the two values and they ended up being the same, however I am struggling to figure out how to do the right endpoint code, I'm not exactly sure what to change.

Thank you.
 
Physics news on Phys.org
ver_mathstats said:
Homework Statement:: Construct two codes using python for the definite integral using a Riemann sum with left endpoints and right endpoints.
Relevant Equations:: [a,b]=[2,5]
f(x)=1/(1+x^2)

Code:
import numpy as np

def num_int(f,a,b,n):
    dx=(b-a)/n
    x=np.arange(a,b,step=dx)
    y=f(x)
    return y.sum()*dx

def rational_func(x):
    return 1/(1+x**2)

print(num_int(rational_func,2,5,10))

Here is my code for the left endpoint, I know this code works because I compared it to an actual calculator the two values and they ended up being the same, however I am struggling to figure out how to do the right endpoint code, I'm not exactly sure what to change.

I would write the code with two integration functions: num_int_left() -- which you have -- and num_int_right() -- which is almost identical to the code you have, with only a small change in one line.

Alternatively, you could have a single function with an additional parameter that indicates whether you want left sums or right sums.

Thank you.
Using the values you entered, your left endpoint Riemann sum calculates the values of f at 2, 2.3, 2.6, 2.9. 3.2, 3.5, 3.8, 4.1, 4.4, and 4.7. For the right endpoint Riemann sum, you want the code to calculate the values at 2.3, 2.6, ..., 4.7, and 5.0. Should be easy enough to figure out how to do that.
 
Mark44 said:
Using the values you entered, your left endpoint Riemann sum calculates the values of f at 2, 2.3, 2.6, 2.9. 3.2, 3.5, 3.8, 4.1, 4.4, and 4.7. For the right endpoint Riemann sum, you want the code to calculate the values at 2.3, 2.6, ..., 4.7, and 5.0. Should be easy enough to figure out how to do that.
Thank you for the help, it works when I change the line y=f(x) to y=f(x+dx).
 
ver_mathstats said:
Thank you for the help, it works when I change the line y=f(x) to y=f(x+dx).
That works, but what I was thinking of was x=np.arange(a + dx,b,step=dx)
 
Mark44 said:
That works, but what I was thinking of was x=np.arange(a + dx,b,step=dx)
Oh okay I understand, thank you.