import numpy as np import math from scipy import integrate def f(x): return math.exp(-x**2) def g(x): return math.exp(-x**2) def func(a,b,n,g): x = np.linspace(a,b,n+1) sum = 0 h =(b-a)/n for i in range(n): if i%2 == 0: sum = sum + 2*g(x[i]) if i%2 != 0: sum = sum + 4*g(x[i]) sum = (h/3)*(sum -g(x[0])-g(x[n])) return sum answer = func(0,1,1000,g) print(answer) value, error = integrate.quad(f,0, 1) print (value,error)
结果
0.7467996075163496
0.7468241328124271 8.291413475940725e-15