Python 第三方模块 科学计算 SciPy模块2 积分,插值

四.Integrate模块
1.接受函数的积分函数
(1)定积分:

求定积分:[<y>,<abserr>,<infodict>,<message>,<explain>=]scipy.integrate.quad(<func>,<a>,<b>[,args=(),full_output=0,epsabs=1.49e-08,epsrel=1.49e-08,limit=50,points=None,weight=None,wvar=None,wopts=None,maxp1=50,limlst=50])
  #通过Fortran库QUADPACK中的技术实现
  #参数说明:
  	func:指定被积函数;为function/scipy.LowLevelCallable
  	a,b:分别指定积分下/上限;float(包括np.inf)
  	  #会被作为第1个参数传给<func>
  	args:指定要传递给<func>的其他参数;tuple(不能是list)/参数
  	full_output:指定是否返回额外信息;int
  	  #为True时还会返回<infodict>
  	epsabs,epsrel:分别指定能容忍的最大绝对/相对误差;float/int
  	  #目标是达到:abs(i-<y>)<=max(epsabs,epsrel*abs(i)),其中i是实际的积分值
  	limit:指定自适应算法中使用的最大子区间数;float/int
  	points:指定函数的间断点(无需排序);为sequence
  	y:返回积分结果;float
  	abserr:返回绝对误差的估计值;float
  	infodict:返回更多相关信息;dict
  	  #仅当full_output=True时被返回

#实例:
>>> def f(x):
...     return x+1
...
>>> integrate.quad(f,1,2)
(2.5, 2.7755575615628914e-14)
>>> def ff(x,y):
...     return x+y
...
>>> integrate.quad(ff,1,2,args=0)
(1.5, 1.6653345369377348e-14)

######################################################################################################################

求向量值函数的定积分:[<res>,<err>,<info>=]scipy.integrate.quad_vec(<f>,<a>,<b>[,epsabs=1e-200,epsrel=1e-08,norm='2',cache_size=100000000.0,limit=10000,workers=1,points=None,quadrature=None,full_output=False])
  #参数说明:其他参数同scipy.integrate.quad()
  	f:指定被积函数;callable
  	norm:指定用于误差估计的向量范数(Vector Norm);"max"/"2"
  	cache_size:指定缓存大小(单位为B);int
  	workers:指定多进程;int/map-like callable
  	quadrature:指定子区间上的积分求法;"gk21"/"gk15"/"trapezoid",默认为"gk21"(有限区间)/"gk15"(无限区间)
  	full_output:指定是否返回额外信息;bool
  	  #为True时还会返回<info>
  	res:返回积分结果;float/array-like
  	err:返回误差估计;float
  	info:返回更多相关信息;dict
  	  #仅当full_output=True时被返回

#实例:
>>> res,err,info=integrate.quad_vec(f,1,2,full_output=True)
>>> res
array([0.  , 2.25, 4.5 ])
>>> err
1.675710553441909e-13
>>> info
_Bunch(neval=63, success=True, status=0, message='Target precision reached.', intervals=array([[1.5, 2. ],
       [1. , 1.5]]), integrals=array([[0.    , 1.3125, 2.625 ],
       [0.    , 0.9375, 1.875 ]]), errors=array([3.25832608e-14, 2.32737577e-14]))

######################################################################################################################

求定积分:[<val>,None=]scipy.integrate.fixed_quad(<func>,<a>,<b>[,args=(),n=5])
  #通过"固定阶数的高斯求积公式"(Fixed-Order Gaussian Quadrature)实现
  #参数说明:<a>/<b>同scipy.integrate.quad()
    func:指定被积函数;callable
    args:指定要传递给<func>的其他参数;为array-like
    n:指定高斯求积公式的阶数(使用n+1个节点);int
    val:返回积分结果;float

#实例:
>>> integrate.fixed_quad(f,1,2,(1.5,))
(1.659002681632464, None)
>>> integrate.fixed_quad(f,1,2,(1.5,),n=6)
(1.6590026851087492, None)
>>> integrate.fixed_quad(f,1,2,(1.5,),n=7)
(1.65900268513502, None)
>>> integrate.fixed_quad(f,1,2,(1.5,),n=8)
(1.6590026851354214, None)
>>> integrate.fixed_quad(f,1,2,(1.5,),n=9)
(1.65900268513543, None)
>>> integrate.fixed_quad(f,1,2,(1.5,),n=10)
(1.65900268513543, None)
>>> integrate.fixed_quad(f,1,2,(1.5,),n=100)
(1.65900268513543, None)

######################################################################################################################

求定积分:[<val>,<err>=]scipy.integrate.quadrature(<func>,<a>,<b>[,args=(),tol=1.49e-08,rtol=1.49e-08,maxiter=50,vec_func=True,miniter=1])
  #通过"固定误差容忍度的高斯求积公式"(Fixed-Tolerance Gaussian Quadrature)实现
  #参数说明:其他参数同scipy.integrate.fixed_quad()
    func:指定被积函数;为function
    tol,rtol:分别指定绝对/相对最低精度改进(停止条件);float
      #若精度改进低于此值,则停止
    maxiter,miniter:指定高斯求积公式的最高/低阶数;int
    vec_func:指定是否为向量值函数;bool
    err:返回最后1次的精度改进值;float

######################################################################################################################

求定积分:[<results>=]scipy.integrate.romberg(<function>,<a>,<b>[,args=(),tol=1.48e-08,rtol=1.48e-08,show=False,divmax=10,vec_func=False])
  #通过"龙贝格求积公式"(Romberg Integration)实现
  #参数说明:其他参数同scipy.integrate.quadrature()
  	function:同scipy.integrate.fixed_quad()<func>
  	show:是否输出积分过程;bool
  	divmax:指定最大外推阶数;int
  	results:返回积分结果;float

#实例:
>>> results=integrate.romberg(lambda x:x**x,1,2)
>>> results
2.0504462345347854
>>> results=integrate.romberg(lambda x:x**x,1,2,show=True)
Romberg integration of <function vectorize1.<locals>.vfunc at 0x00000239F659F940> from [1, 2]

 Steps  StepSize   Results
     1  1.000000  2.500000
     2  0.500000  2.168559  2.058078
     4  0.250000  2.080374  2.050979  2.050506
     8  0.125000  2.057954  2.050481  2.050447  2.050446
    16  0.062500  2.052325  2.050448  2.050446  2.050446  2.050446
    32  0.031250  2.050916  2.050446  2.050446  2.050446  2.050446  2.050446

The final result is 2.0504462345347854 after 33 function evaluations.
>>> results
2.0504462345347854

######################################################################################################################

求牛顿-科茨积分公式所需的权重:[<an>,<B>=]scipy.integrate.newton_cotes(<rn>[,equal=0])
  #通过"牛顿-科茨积分公式"(Newton-Cotes Integration)实现
  #Normally,the Newton-Cotes rules are used on smaller integration regions and a composite rule is used to return the total integral
  #参数说明:
  	rn:指定牛顿-科茨积分公式的阶数(使用n+1个节点);int
  	equal:指定是否等分积分区间;int(1表示强制等分)
  	an:返回权重;1×(<rn>+1) ndarray
  	B:返回误差系数;float

#实例:
>>> def f(x):
...     return np.sin(x)
...
>>> a=0
>>> b=np.pi
>>> exact=2
>>> N=6
>>> x=np.linspace(a,b,N+1)
>>> an,B=integrate.newton_cotes(N,1)
>>> an
array([0.29285714, 1.54285714, 0.19285714, 1.94285714, 0.19285714,
       1.54285714, 0.29285714])
>>> B
-0.0064285714285714285
>>> dx=(b-a)/N
>>> quad=dx*np.sum(an*f(x))
>>> error=abs(quad-exact)
>>> quad
2.000017813636656
>>> error
1.7813636655983345e-05

(2)多重积分:

求二重积分:[<y>,<abserr>=]scipy.integrate.dblquad(<func>,<a>,<b>,<gfun>,<hfun>[,args=(),epsabs=1.49e-08,epsrel=1.49e-08])
  #参数说明:args同scipy.integrate.fixed_quad(),epsabs/epsrel同scipy.integrate.quad()
  	func:指定被积函数;callable,格式为<func>(<y>,<x>,*args,**kwargs)
  	a,b:分别指定<x>的积分下/上限;float
  	gfun,hfun:分别指定<y>的积分下/上限;callable(接受1个参数)/float
  	y:返回积分结果;float
  	abserr:返回误差估计;float

#实例:
>>> def fff(y,x,a):
...     return a*x*y
...
>>> integrate.dblquad(fff,1,2,3,4,args=(3,))#注意:写成(3)会被作为int传入
(15.749999999999998, 2.328937054972335e-13)

######################################################################################################################

求三重积分:[<y>,<abserr>=]scipy.integrate.tplquad(<func>,<a>,<b>,<gfun>,<hfun>,<qfun>,<rfun>[,args=(),epsabs=1.49e-08,epsrel=1.49e-08])
  #参数说明:其他参数同scipy.integrate.dblquad()
    func:格式为<func>(<z>,<y>,<x>,*args,**kwargs),其他同scipy.integrate.dblquad()
    qfun,rfun:分别指定<z>的积分下/上限;为function(接受2个参数)/float

######################################################################################################################

求n重积分:[<result>,<abserr>,<out_dict>=]scipy.integrate.nquad(<func>,<ranges>[,args=None,opts=None,full_output=False])
  #是通过包装scipy.integrate.quad()实现的
  #参数说明:full_output同scipy.integrate.quad_vec()
  	func:指定被积函数;callable(格式为<func>(<x0>...<xn>,*args,**kwargs))/scipy.LowLevelCallable
  	ranges:指定各变量的积分下/上限;为iterable,元素为(<a>,<b>)/callable
  	args:指定要传递给<func>的其他参数;为iterable
  	opts:指定要传递给scipy.integrate.quad()的其他参数;为iterable/dict
  	result:返回积分结果;float
  	abserr:返回绝对误差估计;float
  	out_dict:返回更多相关信息;dict
  	  #仅当full_output=True时被返回

#实例:
>>> def fff(y,x,a):
...     return a*x*y
...
>>> integrate.nquad(fff,((1,2),(3,4)),(1,))
(5.25, 6.657722009550234e-14)
>>> integrate.nquad(fff,((1,2),(3,4)),(1,),full_output=True)
(5.25, 6.657722009550234e-14, {
    
    'neval': 441})

(3)帮助函数:

输出有关scipy.integrate.quad()的额外信息:None=scipy.integrate.quad_explain([output=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>])
  #参数说明:
  	output:指定输出位置;为instance with "write" method(file handle),默认为sys.stdout

#实例:
>>> f=open("E://1.txt",mode="w")
>>> integrate.quad_explain(f)
>>> f.close()

2.接受样本的积分函数:

scipy.integrate.trapezoid(<y>[,x=None,dx=1.0,axis=-1])
scipy.integrate.cumulative_trapezoid(<y>[,x=None,dx=1.0,axis=-1,initial=None])
scipy.integrate.simpson(<y>[,x=None,dx=1,axis=-1,even="avg"])
scipy.integrate.romb(<y>[,dx=1.0,axis=-1,show=False])

3.求解微分方程
(1)求解初值问题:

#以下是函数:
scipy.integrate.solve_ivp(<fun>,<t_span>,<y0>[,method="RK45",t_eval=None,dense_output=False,events=None,vectorized=False,args=None,**options])
#旧的接口:
scipy.integrate.odeint(<func>,<y0>,<t>[,args=(),Dfun=None,col_deriv=0,full_output=0,ml=None,mu=None,rtol=None,atol=None,tcrit=None,h0=0.0,hmax=0.0,hmin=0.0,ixpr=0,mxstep=0,mxhnil=0,mxordn=12,mxords=5,printmessg=0,tfirst=False])


######################################################################################################################
######################################################################################################################

#以下都是类:
class scipy.integrate.RK23(<fun>,<t0>,<y0>,<t_bound>[,max_step=inf,rtol=0.001,atol=1e-06,vectorized=False,first_step=None,**extraneous])
class scipy.integrate.RK45(<fun>,<t0>,<y0>,<t_bound>[,max_step=inf,rtol=0.001,atol=1e-06,vectorized=False,first_step=None,**extraneous])
class scipy.integrate.DOP853(<fun>,<t0>,<y0>,<t_bound>[,max_step=inf,rtol=0.001,atol=1e-06,vectorized=False,first_step=None,**extraneous])
class scipy.integrate.Radau(<fun>,<t0>,<y0>,<t_bound>[,max_step=inf,rtol=0.001,atol=1e-06,jac=None,jac_sparsity=None,vectorized=False,first_step=None,**extraneous])
class scipy.integrate.BDF(<fun>,<t0>,<y0>,<t_bound>[,max_step=inf,rtol=0.001,atol=1e-06,jac=None,jac_sparsity=None,vectorized=False,first_step=None,**extraneous])
class scipy.integrate.LSODA(<fun>,<t0>,<y0>,<t_bound>[,first_step=None,min_step=0.0,max_step=inf,rtol=0.001,atol=1e-06,jac=None,lband=None,uband=None,vectorized=False,**extraneous])
class scipy.integrate.OdeSolver(<fun>,<t0>,<y0>,<t_bound>,<vectorized>[,support_complex=False])
class scipy.integrate.DenseOutput(<t_old>,<t>)
class scipy.integrate.OdeSolution(<ts>,<interpolants>)
#旧的接口:
class scipy.integrate.ode(<f>[,jac=None])
class scipy.integrate.complex_ode(<f>[,jac=None])

(2)求解边值问题:

scipy.integrate.solve_bvp(<fun>,<bc>,<x>,<y>[,p=None,S=None,fun_jac=None,bc_jac=None,tol=0.001,max_nodes=1000,verbose=0,bc_tol=None])

五.Interpolate
1.1维插值:

进行1维插值:<f>=class scipy.interpolate.interp1d(<x>,<y>[,kind='linear',axis=-1,copy=True,bounds_error=None,fill_value=nan,assume_sorted=False])
  #参数说明:
	x:指定样本的x值;1×Ni array-like
	y:指定样本的y值;为N1×...×Ni×...×Nn array-like
	kind:指定插值方法;str/int(指定样条插值的阶数)
	  #str可为"linear"/"nearest"/"nearest-up"/"zero"/"slinear"/"quadratic"/"cubic"/"previous"/"next"/"zero"/"slinear"/"quadratic"/"cubic"
	axis:指定沿<y>的哪个轴进行插值;int
	  #<y>沿该轴的长度应等于<x>的长度
	copy:指定是否在类内创建<x>/<y>的副本;bool
	bounds_error:指定是否禁止外插;bool,默认为False除非fill_value="extrapolate"
	  #为True时,外插时会报错;为False时,外插得到的值由fill_value指定
	fill_value:指定外插时得到的值;float(直接指定值)/array-like(直接指定值)/(array-like,array_like)(分类指定值)/"extrapolate"(进行外推)
	  #详情参见官方文档:https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.interp1d.html#scipy.interpolate.interp1d
	assume_sorted:指定<x>是否为递增序列;bool
	  #为False时,<x>可为任意顺序,并会先被排序;为True时,<x>应为单调递增序列
	f:返回插值函数;为scipy.interpolate.interpolate.interp1d object
	  #然后通过<f>(<x>)即可得到其他x值对应的y值,x为array-like

#实例:
>>> scipy.interpolate.interp1d([1,2,3],[4,5,6])([1.1,2.2])
array([4.1, 5.2])

######################################################################################################################



######################################################################################################################



######################################################################################################################

2.多元插值:

进行2元插值:<yi>=class scipy.interpolate.griddata(<points>,<values>,<xi>[,method='linear',fill_value=nan,rescale=False])
  #参数说明:
  	points:指定样本点的位置;为N×k array-like(每行为1个点)
  	values:指定样本点处的函数值;1×N array-like
  	method:指定插值方法;"linear"/"nearest"/"cubic"
  	fill_value:指定外插时得到的值;float
  	  #method="nearest"时无效
  	rescale:指定是否对输入的数据进行归一化(Min-Max Normalization);bool
  	  #原文为:Rescale points to unit cube before performing interpolation
  	  #当各维度数据的单位不可比或数据的值存在极大差异时很有用
  	xi:指定要插值的点;为M×k array-like(每行为1个点)
	yi:返回要插值的点处的插值函数值;1×M ndarray

3.样条插值
(1)1维样条插值:


(2)2维样条插值:


猜你喜欢

转载自blog.csdn.net/weixin_46131409/article/details/113941762