[关闭]
@kailaix 2017-04-10T06:54:49.000000Z 字数 1745 阅读 799

Singularity Integration

LinearAlgebra


  1. from numpy import *
  2. from matplotlib.pyplot import *
  3. from numpy.linalg import *
  4. 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.

  1. def f1(x):
  2. if isinstance(x,ndarray):
  3. y = zeros_like(x)
  4. for i in range(x.shape[0]):
  5. y[i] = 1./sqrt(sin(x[i]))
  6. else:
  7. y = 1./sqrt(sin(x))
  8. return y

We use simpson rule to do numerical integration.

  1. def simpson_quad(func,a,b,tol=1e-6):
  2. n = int((b-a)/tol)
  3. s = 0.0
  4. x = a+tol*arange(n+1)
  5. f = func(x)
  6. m = a+tol*(0.5+arange(n))
  7. fm = func(m)
  8. for i in range(n):
  9. s +=tol/6.0*(f[i]+4*fm[i]+f[i+1])
  10. return s

For example, we will have

  1. simpson_quad(lambda x:x, 0, 1)
0.49999999999999994

Now we compute the singular integration.

  1. print(simpson_quad(f1, 1e-5,1,1e-6))
  2. print(simpson_quad(f1, 1e-6,1,1e-6))
  3. 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.

  1. def f2(x):
  2. y = zeros_like(x)
  3. for i in range(x.shape[0]):
  4. t = sqrt(sin(x[i]))
  5. s = sqrt(x[i])
  6. if allclose(t,0) or allclose(s,0):
  7. y[i] = 0.0
  8. else:
  9. y[i] = 1./t-1./s
  10. return y
  1. simpson_quad(f2,0,1,1e-4)+2
2.0348053192075901
  1. simpson_quad(f2,0,1,1e-5)+2
2.0348044178614586
  1. simpson_quad(f2,0,1,1e-6)+2
2.0348053192075706

We see it converges rather quickly here.

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注