与黎曼和的数值积分(Python)

时间:2022-09-25 20:22: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.

我有下面的代码,但是当它运行时,它会返回0它会返回一个值2,因为我正在尝试在区间[0,]中对sin(x)积分。请建议。

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)

2 个解决方案

#1


4  

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.

1/2在python2。x中是0。它执行整数除法和四舍五入。你可以用0。5或1。1 /2来代替。

#2


0  

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.

在浮点数方程中使用整数值时,您应该小心,如果您有一个整数,那么使用float()将其转换为整数值。如果你的代码中有一个常数,比如10,那么把它写成小数…10.0。

#1


4  

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.

1/2在python2。x中是0。它执行整数除法和四舍五入。你可以用0。5或1。1 /2来代替。

#2


0  

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.

在浮点数方程中使用整数值时,您应该小心,如果您有一个整数,那么使用float()将其转换为整数值。如果你的代码中有一个常数,比如10,那么把它写成小数…10.0。