用Riemann Sum(Python)进行数值积分 [英] Numerical Integration with Riemann Sum (Python)
本文介绍了用Riemann Sum(Python)进行数值积分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码,但运行时会给出0.0
由于我正在尝试在间隔[0, pi]
中对sin(x)
进行积分,因此它应该返回2
的值.
请告知.
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/2
在python 2.x中为0
.它正在执行整数除法和四舍五入.您可以通过使用0.5
或1.0/2
来获得所需的内容.
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.
这篇关于用Riemann Sum(Python)进行数值积分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文