我已经实现了这个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