[英]Simpson's Rule returning 0
I coded a function for Simpson's Rule of numerical integration. 我为辛普森数值积分法则编写了函数。 For values of n
more than or equal to 34, the function returns 0. 对于大于或等于34的n
值,该函数返回0。
Here, n
is the number of intervals, a
is the start point, and b
is the end point. 在此, 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))
I am not sure why this is happening. 我不确定为什么会这样。 I also coded a function for the Trapezoidal Method and that does not return 0 even when n
= 50. What is going on here? 我还为梯形方法编写了一个函数,即使n
= 50也不会返回0。这是怎么回事?
Wikipedia has the code for Simpson's rule in Python : Wikipedia具有Python中Simpson规则的代码:
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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.