微分法计算定积分
所有积分区间都分割成100万份,计算以下四个常用积分:
from math import sin from math import log from math import exp from math import pi from math import e N=1000000 def interalSin(a,b): '''sin(x)在区间[a,b]上的定积分''' d=(b-a)/N r=0 for i in range(N): r+=d*sin(a+i*d+d/2) return r def interalLn(a,b): '''ln(x)在区间[a,b]上的定积分''' d=(b-a)/N r=0 for i in range(N): r+=d*log(a+i*d+d/2) return r def interalAbs(a,b): '''ln(x)在区间[a,b]上的定积分''' d=(b-a)/N r=0 for i in range(N): r+=d*abs(a+i*d+d/2) return r def interalExp(a,b): '''e^x在区间[a,b]上的定积分''' d=(b-a)/N r=0 for i in range(N): r+=d*exp(a+i*d+d/2) return r print(interalSin(0,pi/2)) print(interalLn(1,e)) print(interalAbs(-1,1)) print(interalExp(-1,1),end='\n\n') print('e-1/e=') print(e-1/e) #执行结果: ''' 1.0000000000000981 1.0000000000000977 1.0000000000000002 2.3504023872872146 e-1/e= 2.3504023872876028 >>> '''
注:积分区间微分成100万份,就能得到小数点后12位的精度。
自定义函数作函数的形参:
from math import sin from math import log from math import exp from math import pi from math import e N=1000000 def Sinx(x): return sin(x) def Ln_x(x): return log(x) def Absx(x): return abs(x) def Expx(x): return exp(x) def Interal(func,a,b): '''func(x)在区间[a,b]上的定积分''' d=(b-a)/N r=0 for i in range(N): r+=d*func(a+i*d+d/2) return r print(Interal(Sinx,0,pi/2)) print(Interal(Ln_x,1,e)) print(Interal(Absx,-1,1)) print(Interal(Expx,-1,1))
直接用库函数作函数的形参:
from math import sin from math import log from math import exp from math import pi from math import e N=1000000 def Interal(func,a,b): '''func(x)在区间[a,b]上的定积分''' d=(b-a)/N r=0 for i in range(N): r+=d*func(a+i*d+d/2) return r print(Interal(sin,0,pi/2)) print(Interal(log,1,e)) print(Interal(abs,-1,1)) print(Interal(exp,-1,1))
用lambda函数表达复合函数,并做形参计算定积分:
用以下两个题目做示例:
from math import pi from math import sin from math import cos from math import log from math import sqrt N=1000000 fx=lambda x:sqrt(1-sin(2*x)) gx=lambda x:sin(x)/(1+sin(x)+cos(x)) def Interal(func,a,b): '''func(x)在区间[a,b]上的定积分''' d=(b-a)/N r=0 for i in range(N): r+=d*func(a+i*d+d/2) return r print(Interal(fx,0,pi/2)) print(2*sqrt(2)-2) #对比答案 print() print(Interal(gx,0,pi/2)) print((pi/2-log(2))/2) #对比答案 ''' 0.8284271247463156 0.8284271247461903 0.43882457311750606 0.43882457311747564 >>> '''
附:形参个数不定
可以使用*args或**args,但是一定要把*args放到最后面。
def plus(*args): tmp=0 for i in args: tmp+=i return tmp def mul_p(fn,x,*args): return x*fn(*args) print(plus(1,2,3,4,5,6,7,8,9,10)) print(mul_p(plus,10,1,2,3,4,5,6,7,8,9,10)) #执行结果: ''' 55 550 >>> '''