Python中的数值积分有什么错误?

2024-09-27 22:21:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试将cos(x)从0积分到2pi,但没有找到0。你知道吗

我的代码使用这个数值积分:

def rectangles(f,a,b,n) :
    h=(b-a)/n/1.0
    print h
    z=0.0
    for i in range(n) :
        z=z+f(a+i*h)
    return h*z

功能是:

def f1(x):
    return cos(x)

我使用mpmath biblio:

from mpmath import *
mp.dps=300; mp.pretty=True

电话是:

rectangles(f1,0.0,2.0*pi,100000)

从0到π/2是可以的,从π/2到π,等等,但是如果我想从0到2pi,我会找到:-4.81。你知道吗

这很奇怪,因为如果我写1.9999*π或2.00001*π就行了!你知道吗


Tags: 代码in功能forreturndefrangemp
1条回答
网友
1楼 · 发布于 2024-09-27 22:21:44

but if I want from 0 to 2pi I find: -4.81.

不,你得到了

>>> rectangles(f1,0.0,2.0*pi,100000)
0.000062831853071795864[boring digits deleted]...
-4.81306306411824111[boring digits deleted]...1775099222873051479e-301

而-4.813e-301=-4.813*10^(-301)非常非常接近于零。你知道吗

[旁白:如果ban都是整数,那么h=(b-a)/n/1.0中的/1.0没有多大帮助,因为除法已经失去了精度。]

相关问题 更多 >

    热门问题