@kailaix
2017-04-10T06:54:49.000000Z
字数 1745
阅读 1117
LinearAlgebra
from numpy import *from matplotlib.pyplot import *from numpy.linalg import *from scipy.integrate import *
Here is a simple example illustrating how to do numerical integration for singular functions.
We will consider
A naive idea is to do
where is a small number.
def f1(x):if isinstance(x,ndarray):y = zeros_like(x)for i in range(x.shape[0]):y[i] = 1./sqrt(sin(x[i]))else:y = 1./sqrt(sin(x))return y
We use simpson rule to do numerical integration.
def simpson_quad(func,a,b,tol=1e-6):n = int((b-a)/tol)s = 0.0x = a+tol*arange(n+1)f = func(x)m = a+tol*(0.5+arange(n))fm = func(m)for i in range(n):s +=tol/6.0*(f[i]+4*fm[i]+f[i+1])return s
For example, we will have
simpson_quad(lambda x:x, 0, 1)
0.49999999999999994
Now we compute the singular integration.
print(simpson_quad(f1, 1e-5,1,1e-6))print(simpson_quad(f1, 1e-6,1,1e-6))print(simpson_quad(f1, 1e-7,1,1e-6))
2.02848076409
2.0328057929
2.03425369423
We see even if we use steps and only disgard we may have error up to . It is huge indeed.
We will now split
The latter can be computed as
and for the former, we compute with simpson's rule.
def f2(x):y = zeros_like(x)for i in range(x.shape[0]):t = sqrt(sin(x[i]))s = sqrt(x[i])if allclose(t,0) or allclose(s,0):y[i] = 0.0else:y[i] = 1./t-1./sreturn y
simpson_quad(f2,0,1,1e-4)+2
2.0348053192075901
simpson_quad(f2,0,1,1e-5)+2
2.0348044178614586
simpson_quad(f2,0,1,1e-6)+2
2.0348053192075706
We see it converges rather quickly here.