我正在使用R的集成功能,但是被积函数给了我一些麻烦(它有一个奇点)。考虑一下,
distrib <- function(x){
dnorm(x, mean=700,sd=50)
}
phi <- function(nu, epsilon=20, maxi=Inf){
fun <- function(nup) {
lambdap <- 1e7/nup
distrib(lambdap) / (nup*(nup - nu))
}
# first part: from epsilon to nu - epsilon
I1 <- integrate(fun, epsilon, nu-epsilon, rel.tol = 1e-8,
subdivisions = 200L)
# second part: from nu + epsilon to Infty
I2 <- integrate(fun, nu+epsilon, maxi, rel.tol = 1e-8,
subdivisions = 200L)
I1$value + I2$value
}
x <- seq(1e7/500, 1e7/1000, length=200)
phi1 <- sapply(x, phi)
phi1 <- sapply(x, phi, epsilon=5)
#Error in integrate(fun, epsilon, nu - epsilon, rel.tol = 1e-08, subdivisions = #200L) :
# the integral is probably divergent
是否有更好的方法来计算R中的这些主值,而不是使用截止参数并手动调整直到它给出结果(不一定准确)?
答案 0 :(得分:1)
如果考虑以奇点为中心的区间积分, 你可以使用变量的变化来对齐被积函数:奇点消失了, 详见论文Numerical evaluation of a generalized Cauchy principal value (A. Nyiri and L. Bayanyi, 1999)。
# Principal value of \( \int_{x_0-a}^{x_0+a} \dfrac{ f(x) }{ h(x) - h(x0) } dx \)
pv_integrate <- function( f, h, x0, a, epsilon = 1e-6 ) {
# Estimate the derivatives of f and h
f1 <- ( f(x0+epsilon) - f(x0-epsilon) ) / ( 2 * epsilon )
h1 <- ( h(x0+epsilon) - h(x0-epsilon) ) / ( 2 * epsilon )
h2 <- ( h(x0+epsilon) + h(x0-epsilon) - 2 * h(x0) ) / epsilon^2
# Function to integrate.
# We just "symmetrize" the integrand, to get rid of the singularity,
# but, to be able to integrate it numerically,
# we have to provide a value at the singularity.
# Details: http://mat76.mat.uni-miskolc.hu/~mnotes/downloader.php?article=mmn_16.pdf
g <- function(u)
ifelse( u != 0,
f( x0 - u ) / ( h(x0 - u) - h(x0) ) + f( x0 + u ) / ( h(x0+u) - h(x0) ),
2 * f1 / h1 - f(x0) * h2 / h1^2
)
integrate( g, 0, a )
}
# Compare with the numeric results in the article
pv_integrate( function(x) 1, function(x) x, 0, 1 ) # 0
pv_integrate( function(x) 1, function(x) x^3, 1, .5 ) # -0.3425633
pv_integrate( function(x) exp(x), function(x) x, 0, 1 ) # 2.114502
pv_integrate( function(x) x^2, function(x) x^4, 1, .5 ) # 0.1318667