示例求f(x) = e^x在[0,1]区间上精度为10e-5的积分
import math
from scipy.misc import derivative
def sum_fun_x(x, func): # 累加项
return sum([func(each) for each in x])
def integral(a, b, n, func): # 梯形复化公式
h = (b - a)/float(n)
x = [a + i*h for i in range(1, n)]
return h/2 * (func(a) + 2 * sum_fun_x(x, func) + func(b))
def func(x): # 函数
return math.pow(math.e,x)
def calculN(h,p): # 根据精度得到n
n = 2
tp = math.fabs(math.pow(h, 2) * (derivative(func, b) - derivative(func, a)))
tp /= n * n
while(tp > p):
tp *= n * n
n += 1
tp /= n * n
return n
a, b = 0, 1 # 区间值
p = 10e-5 # 精度
n = calculN(b - a,p)
print(integral(a, b, n, func))