Simpson 与 Python 的集成:无法按预期获得输出

问题描述

我已经实现了这个 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,6,2],[lambda x:x**2,5,6],[lambda x:math.sin(x),math.pi,4],[lambda x:1/x,6]]

    for d in data:
        f,n = d
        print(simpson(f,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

解决方法

我是否正确地将第三个数字解释为包括终点在内的总分?如果是 - 以下工作。您使 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,n)[1:-1]))
    return ((b - a) / (3 * n)) * (fn(a) + 2*ans + fn(b))

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

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

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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...