簡體   English   中英

辛普森規則返回0

[英]Simpson's Rule returning 0

我為辛普森數值積分法則編寫了函數。 對於大於或等於34的n值,該函數返回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。這是怎么回事?

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM