Swift 的 Foundation 导入中是否有可用的反误差函数?
Is there an Inverse Error Function available in Swift's Foundation import?
我在 Swift 中使用 erf
函数,像这样:
import Foundation
erf(2)
还有反误差函数吗?
我们的标准库中没有这样的函数。但是这里是这个函数的一个实现-
https://github.com/antelopeusersgroup/antelope_contrib/blob/master/lib/location/libgenloc/erfinv.c
HTH.
OP 在 GitHub 上发布的解决方案:
func erfinv(y: Double) -> Double {
let center = 0.7
let a = [ 0.886226899, -1.645349621, 0.914624893, -0.140543331]
let b = [-2.118377725, 1.442710462, -0.329097515, 0.012229801]
let c = [-1.970840454, -1.624906493, 3.429567803, 1.641345311]
let d = [ 3.543889200, 1.637067800]
if abs(y) <= center {
let z = pow(y,2)
let num = (((a[3]*z + a[2])*z + a[1])*z) + a[0]
let den = ((((b[3]*z + b[2])*z + b[1])*z + b[0])*z + 1.0)
var x = y*num/den
x = x - (erf(x) - y)/(2.0/sqrt(.pi)*exp(-x*x))
x = x - (erf(x) - y)/(2.0/sqrt(.pi)*exp(-x*x))
return x
}
else if abs(y) > center && abs(y) < 1.0 {
let z = pow(-log((1.0-abs(y))/2),0.5)
let num = ((c[3]*z + c[2])*z + c[1])*z + c[0]
let den = (d[1]*z + d[0])*z + 1
// should use the sign function instead of pow(pow(y,2),0.5)
var x = y/pow(pow(y,2),0.5)*num/den
x = x - (erf(x) - y)/(2.0/sqrt(.pi)*exp(-x*x))
x = x - (erf(x) - y)/(2.0/sqrt(.pi)*exp(-x*x))
return x
} else if abs(y) == 1 {
return y * Double(Int.max)
} else {
return .nan
}
}
Swift 似乎没有。这有一个算法可以翻译成 Swift:
Need code for Inverse Error Function
此外,Ch 6.2.2 或数值解,3e 有一个算法:
我在 Swift 中使用 erf
函数,像这样:
import Foundation
erf(2)
还有反误差函数吗?
我们的标准库中没有这样的函数。但是这里是这个函数的一个实现-
https://github.com/antelopeusersgroup/antelope_contrib/blob/master/lib/location/libgenloc/erfinv.c
HTH.
OP 在 GitHub 上发布的解决方案:
func erfinv(y: Double) -> Double {
let center = 0.7
let a = [ 0.886226899, -1.645349621, 0.914624893, -0.140543331]
let b = [-2.118377725, 1.442710462, -0.329097515, 0.012229801]
let c = [-1.970840454, -1.624906493, 3.429567803, 1.641345311]
let d = [ 3.543889200, 1.637067800]
if abs(y) <= center {
let z = pow(y,2)
let num = (((a[3]*z + a[2])*z + a[1])*z) + a[0]
let den = ((((b[3]*z + b[2])*z + b[1])*z + b[0])*z + 1.0)
var x = y*num/den
x = x - (erf(x) - y)/(2.0/sqrt(.pi)*exp(-x*x))
x = x - (erf(x) - y)/(2.0/sqrt(.pi)*exp(-x*x))
return x
}
else if abs(y) > center && abs(y) < 1.0 {
let z = pow(-log((1.0-abs(y))/2),0.5)
let num = ((c[3]*z + c[2])*z + c[1])*z + c[0]
let den = (d[1]*z + d[0])*z + 1
// should use the sign function instead of pow(pow(y,2),0.5)
var x = y/pow(pow(y,2),0.5)*num/den
x = x - (erf(x) - y)/(2.0/sqrt(.pi)*exp(-x*x))
x = x - (erf(x) - y)/(2.0/sqrt(.pi)*exp(-x*x))
return x
} else if abs(y) == 1 {
return y * Double(Int.max)
} else {
return .nan
}
}
Swift 似乎没有。这有一个算法可以翻译成 Swift:
Need code for Inverse Error Function
此外,Ch 6.2.2 或数值解,3e 有一个算法: