Numerical Integration with Riemann Sum (Python)

只谈情不闲聊 提交于 2019-12-11 03:05:19

问题


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 math import sin, pi

def Rsum(a,b):
    for i in range(1001):
        s = 0
        delx = float((b-a)/1000)
        g = i*delx
        h = (i+1)*delx

        y_i = float(sin(a+g))
        y_ii = float(sin(a+h))
        s += 1/2 * (y_i + y_ii) * delx

    return s

print Rsum(0,pi)

回答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.




回答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.



来源:https://stackoverflow.com/questions/17687756/numerical-integration-with-riemann-sum-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!