如何在Ruby中计算数字的NORMSINV(0到1之间)和数字的平方根?
我正在使用Excel中的函数,如下所示,我需要在Ruby中实现它。
=NORMSINV(A1)
=SQRT(A1)
答案 0 :(得分:1)
正如c650在评论中指出的那样,x
的平方根只是
x**0.5
Martin Vidner为您提供link to a decent algorithm近似正态分布。为方便起见,我把它移植到Ruby:
# algorithm ported from http://www.source-code.biz/snippets/vbasic/9.htm
A1 = -39.6968302866538
A2 = 220.946098424521
A3 = -275.928510446969
A4 = 138.357751867269
A5 = -30.6647980661472
A6 = 2.50662827745924
B1 = -54.4760987982241
B2 = 161.585836858041
B3 = -155.698979859887
B4 = 66.8013118877197
B5 = -13.2806815528857
C1 = -7.78489400243029E-03
C2 = -0.322396458041136
C3 = -2.40075827716184
C4 = -2.54973253934373
C5 = 4.37466414146497
C6 = 2.93816398269878
D1 = 7.78469570904146E-03
D2 = 0.32246712907004
D3 = 2.445134137143
D4 = 3.75440866190742
P_low = 0.02425
P_high = 1 - P_low
def phi(p)
raise ArgumentError if p < 0 || p > 1
if p < P_low
q = (-2 * Math::log(p))**0.5
(((((C1 * q + C2) * q + C3) * q + C4) * q + C5) * q + C6) /
((((D1 * q + D2) * q + D3) * q + D4) * q + 1)
elsif p <= P_high
q = p - 0.5
r = q * q
(((((A1 * r + A2) * r + A3) * r + A4) * r + A5) * r + A6) * q /
(((((B1 * r + B2) * r + B3) * r + B4) * r + B5) * r + 1)
else
q = (-2 * Math::log(1 - p))**0.5
(((((C1 * q + C2) * q + C3) * q + C4) * q + C5) * q + C6) /
((((D1 * q + D2) * q + D3) * q + D4) * q + 1)
end
end