-1

我已经实现了这个even()& simpson(),但无法获得所需的输出。其次得到错误([lambda x:1/x, 1, 11, 6]]) ZeroDivisionError: division by zero,无法理解这个错误

import math
import matplotlib
import matplotlib.pyplot as plt
import numpy as np

def even(x):
    if x % 2 == 0:
        return 2
    else:
        return 4

def simpson(fn,a,b,n):
    ans = 0

    for x in range(1, n):
        ans = ans + even(x) * fn(x)
    return ((b - a) / (3 * n)) * (ans + fn(0) + fn(n))

    

if __name__ == "__main__":
    """
    The code in "__main__" is not being graded, but a tool for you to test 
    your code outside of the `test_a8.py`. Feel free to add print statements. 
    """

    data = [[lambda x:3*(x**2)+1, 0,6,2],
            [lambda x:x**2,0,5,6],
            [lambda x:math.sin(x), 0,math.pi, 4],
            [lambda x:1/x, 1, 11, 6]]

    for d in data:
        f,a,b,n = d
        print(simpson(f,a,b,n))

    t = np.arange(0.0, 10.0,.1)
    fig,ax = plt.subplots()
    s = np.arange(0,6.1,.1)
    ax.plot(t, (lambda t: 3*(t**2) + 1)(t),'g')
    plt.fill_between(s,(lambda t: 3*(t**2) + 1)(s))
    ax.grid()
    ax.set(xlabel ="x", ylabel=r"$f(x)=3x^2 + 1$",
        title = r"Area under the curve $\int_0^6\,f(x)$")

    plt.show()

我正在尝试这样的预期输出

222.0
41.66666666666667
2.0045597549844207
2.4491973405016885
4

1 回答 1

0

我是否正确地将第三个数字解释为总分,包括结束?如果是 - 以下工作。您使even函数太重(不需要if,仅需要整数评估)。您的代码的主要问题是您x仅循环整数点并从零开始(当然,参数ab应该是界限)。

import math
import numpy as np

def simpson(fn,a,b,n):
    # n = n + 2 # uncomment this line if only inner points are included in n
    ans = sum((2-i%2)*fn(x) for i,x in enumerate(np.linspace(a,b,n)[1:-1]))
    return ((b - a) / (3 * n)) * (fn(a) + 2*ans + fn(b))

data = [[lambda x:3*(x**2)+1, 0,6,2],
        [lambda x:x**2,0,5,6],
        [lambda x:math.sin(x), 0,math.pi, 4],
        [lambda x:1/x, 1, 11, 6]]

for d in data:
    f,a,b,n = d
    print(simpson(f,a,b,n))

不要期望您提供的输出。您应该为每个范围指定至少 30-50 个点以获得接近准确的结果,2-6 太小了。如果您使用 100 点,结果将接近预期。

于 2021-03-29T19:37:19.310 回答