我为辛普森数值积分规则编写了一个函数。对于n大于或等于34的值,该函数返回0。
这里,n是间隔数,a是起点,b是终点。
import math
def simpsons(f, a,b,n):
x = []
h = (b-a)/n
for i in range(n+1):
x.append(a+i*h)
I=0
for i in range(1,(n/2)+1):
I+=f(x[2*i-2])+4*f(x[2*i-1])+f(x[2*i])
return I*(h/3)
def func(x):
return (x**(3/2))/(math.cosh(x))
x = []
print(simpsons(func,0,100,34))我不确定为什么会发生这种情况。我还为梯形方法编写了一个函数,即使当n =50时它也不会返回0。这里发生什么事情?
发布于 2015-08-27 01:55:55
维基百科用Python编写了辛普森规则的代码:
from __future__ import division # Python 2 compatibility
import math
def simpson(f, a, b, n):
"""Approximates the definite integral of f from a to b by the
composite Simpson's rule, using n subintervals (with n even)"""
if n % 2:
raise ValueError("n must be even (received n=%d)" % n)
h = (b - a) / n
s = f(a) + f(b)
for i in range(1, n, 2):
s += 4 * f(a + i * h)
for i in range(2, n-1, 2):
s += 2 * f(a + i * h)
return s * h / 3
def func(x):
return (x**(3/2))/(math.cosh(x))https://stackoverflow.com/questions/32233145
复制相似问题