Numerical Integration With Riemann Sum (python)
I have the following code but when it is run, it gives 0.0 It should return a value of 2 since I am attempting to integrate sin(x) in the interval [0, pi]. Please advise. from mat
Solution 1:
1/2
is 0
in python 2.x. It is performing integer division and rounding down. You can get what you want by using 0.5
or 1.0/2
instead.
Solution 2:
Try this:
from math import sin, pi
def Rsum(a,b):
for i in range(1001):
s = 0.0
delx = float(b-a)/1000.0
g = i*delx
h = (i+1.0)*delx
y_i = float(sin(a+g))
y_ii = float(sin(a+h))
s += 1.0/2.0 * (y_i + y_ii) * delx
#s += 1/2 * (sin(a+i*delx) + sin(a+(i+1)*delx)) * delx
return s
print Rsum(0,pi)
You should be careful about using integer values in floating point equations, if you have an integer, then convert it with float()
. If you have a constant in your code like 10
then make it decimal... 10.0
.
Post a Comment for "Numerical Integration With Riemann Sum (python)"