Skip to content

Commit f60ba6f

Browse files
committed
BigMath.erf and BigMath.erfc with bit burst algorithm
1 parent c5fbed8 commit f60ba6f

2 files changed

Lines changed: 235 additions & 32 deletions

File tree

lib/bigdecimal/math.rb

Lines changed: 226 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -609,16 +609,11 @@ def erf(x, prec)
609609
xf = x.to_f
610610
log10_erfc = -xf ** 2 / Math.log(10) - Math.log10(xf * Math::PI ** 0.5)
611611
erfc_prec = [prec + log10_erfc.ceil, 1].max
612-
erfc = _erfc_asymptotic(x, erfc_prec)
612+
erfc = _erfc_bit_burst(x, erfc_prec + BigDecimal.double_fig)
613613
return BigDecimal(1).sub(erfc, prec) if erfc
614614
end
615615

616-
prec2 = prec + BigDecimal.double_fig
617-
x_smallprec = x.mult(1, Integer.sqrt(prec2) / 2)
618-
# Taylor series of x with small precision is fast
619-
erf1 = _erf_taylor(x_smallprec, BigDecimal(0), BigDecimal(0), prec2)
620-
# Taylor series converges quickly for small x
621-
_erf_taylor(x - x_smallprec, x_smallprec, erf1, prec2).mult(1, prec)
616+
_erf_bit_burst(x, prec + BigDecimal.double_fig).mult(1, prec)
622617
end
623618

624619
# call-seq:
@@ -641,20 +636,81 @@ def erfc(x, prec)
641636
return BigDecimal(0) if x > 5000000000 # erfc(5000000000) < 1e-10000000000000000000 (underflow)
642637

643638
if x >= 8
644-
y = _erfc_asymptotic(x, prec)
639+
y = _erfc_bit_burst(x, prec + BigDecimal.double_fig)
645640
return y.mult(1, prec) if y
646641
end
647642

648643
# erfc(x) = 1 - erf(x) < exp(-x**2)/x/sqrt(pi)
649644
# Precision of erf(x) needs about log10(exp(-x**2)) extra digits
650645
log10 = 2.302585092994046
651646
high_prec = prec + BigDecimal.double_fig + (x.ceil**2 / log10).ceil
652-
BigDecimal(1).sub(erf(x, high_prec), prec)
647+
BigDecimal(1).sub(_erf_bit_burst(x, high_prec), prec)
648+
end
649+
650+
# Calculates erf(x) using bit-burst algorithm.
651+
private_class_method def _erf_bit_burst(x, prec) # :nodoc:
652+
x = BigDecimal::Internal.coerce_to_bigdecimal(x, prec, :erf)
653+
prec = BigDecimal::Internal.coerce_validate_prec(prec, :erf)
654+
655+
return BigDecimal(0) if x > 5000000000 # erfc underflows
656+
x = x.mult(1, [prec - (x.ceil**2/Math.log(10)).floor, 1].max)
657+
658+
calculated_x = BigDecimal(0)
659+
erf_exp2 = BigDecimal(0)
660+
digits = 8
661+
scale = 2 * exp(-x.mult(x, prec), prec).div(PI(prec).sqrt(prec), prec)
662+
663+
until x.zero?
664+
partial = x.truncate(digits)
665+
digits *= 2
666+
next if partial.zero?
667+
668+
erf_exp2 = _erf_exp2_binary_splitting(partial, calculated_x, erf_exp2, prec)
669+
calculated_x += partial
670+
x -= partial
671+
end
672+
erf_exp2.mult(scale, prec)
673+
end
674+
675+
# Calculates erfc(x) using bit-burst algorithm.
676+
private_class_method def _erfc_bit_burst(x, prec) # :nodoc:
677+
digits = (x.exponent + 1) * 40
678+
679+
calculated_x = x.truncate(digits)
680+
f = _erfc_exp2_asymptotic_binary_splitting(calculated_x, prec)
681+
return unless f
682+
683+
scale = 2 * exp(-x.mult(x, prec), prec).div(PI(prec).sqrt(prec), prec)
684+
x -= calculated_x
685+
686+
until x.zero?
687+
digits *= 2
688+
partial = x.truncate(digits)
689+
next if partial.zero?
690+
691+
f = _erfc_exp2_inv_inv_binary_splitting(partial, calculated_x, f, prec)
692+
calculated_x += partial
693+
x -= partial
694+
end
695+
f.mult(scale, prec)
696+
end
697+
698+
# Matrix multiplication for binary splitting method in erf/erfc calculation
699+
private_class_method def _bs_matrix_mult(m1, m2, size, prec) # :nodoc:
700+
(size * size).times.map do |i|
701+
size.times.map do |k|
702+
m1[i / size * size + k].mult(m2[size * k + i % size], prec)
703+
end.reduce {|a, b| a.add(b, prec) }
704+
end
705+
end
706+
707+
# Matrix/Vector weighted sum for binary splitting method in erf/erfc calculation
708+
private_class_method def _bs_weighted_sum(m1, w1, m2, w2, prec) # :nodoc:
709+
m1.zip(m2).map {|v1, v2| (v1 * w1).add(v2 * w2, prec) }
653710
end
654711

655-
# Calculates erf(x + a)
656-
private_class_method def _erf_taylor(x, a, erf_a, prec) # :nodoc:
657-
return erf_a if x.zero?
712+
# Calculates Taylor expansion of erf(x+a)*exp((x+a)**2)*sqrt(pi)/2 with binary splitting method.
713+
private_class_method def _erf_exp2_binary_splitting(x, a, f_a, prec) # :nodoc:
658714
# Let f(x+a) = erf(x+a)*exp((x+a)**2)*sqrt(pi)/2
659715
# = c0 + c1*x + c2*x**2 + c3*x**3 + c4*x**4 + ...
660716
# f'(x+a) = 1+2*(x+a)*f(x+a)
@@ -669,22 +725,64 @@ def erfc(x, prec)
669725
#
670726
# All coefficients are positive when a >= 0
671727

672-
scale = BigDecimal(2).div(sqrt(PI(prec), prec), prec)
673-
c_prev = erf_a.div(scale.mult(exp(-a*a, prec), prec), prec)
674-
c_next = (2 * a * c_prev).add(1, prec).mult(x, prec)
675-
sum = c_prev.add(c_next, prec)
728+
log10f = Math.log(10)
729+
cexponent = Math.log10([2 * a, Math.sqrt(2)].max.to_f) + BigDecimal::Internal.float_log(x.abs) / log10f
676730

677-
2.step do |k|
678-
cn = (c_prev.mult(x, prec) + a * c_next).mult(2, prec).mult(x, prec).div(k, prec)
679-
sum = sum.add(cn, prec)
680-
c_prev, c_next = c_next, cn
681-
break if [c_prev, c_next].all? { |c| c.zero? || (c.exponent < sum.exponent - prec) }
731+
steps = BigDecimal.save_exception_mode do
732+
BigDecimal.mode(BigDecimal::EXCEPTION_UNDERFLOW, false)
733+
(2..).bsearch do |n|
734+
x.to_f ** 2 < n && n * cexponent + Math.lgamma(n / 2)[0] / log10f + n * Math.log10(2) - Math.lgamma(n - 1)[0] / log10f < -prec + x.to_f**2 / log10f
735+
end
682736
end
683-
value = sum.mult(scale.mult(exp(-(x + a).mult(x + a, prec), prec), prec), prec)
684-
value > 1 ? BigDecimal(1) : value
737+
738+
if a == 0
739+
# Simple calculation for special case
740+
denominators = (steps / 2).times.map {|i| 2 * i + 3 }
741+
return x.mult(1 + BigDecimal::Internal.taylor_sum_binary_splitting(2 * x * x, denominators, prec), prec)
742+
end
743+
744+
# First, calculate a matrix that represents the sum of the Taylor series:
745+
# SumMatrix = (((((...+I)x*M4+I)*x*M3+I)*M2*x+I)*M1*x+I)
746+
# Where Mi is a 2x2 matrix that generates the next coefficients of Taylor series:
747+
# Vector(c4, c5) = M4*M3*M2*M1*Vector(c0, c1)
748+
# And then calculates:
749+
# SumMatrix * Vector(c0, c1) = Vector(c0+c1*x+c2*x**2+..., _)
750+
# In this binary splitting method, adjacent two operations are combined into one repeatedly.
751+
# ((...) * x * A + B) / C is the form of each operation. A and B are 2x2 matrices, C is a scalar.
752+
zero = BigDecimal(0)
753+
two = BigDecimal(2)
754+
two_a = two * a
755+
operations = steps.times.map do |i|
756+
n = BigDecimal(2 + i)
757+
[[zero, n, two, two_a], [n, zero, zero, n], n]
758+
end
759+
760+
while operations.size > 1
761+
xpow = xpow ? xpow.mult(xpow, prec) : x.mult(1, prec)
762+
operations = operations.each_slice(2).map do |op1, op2|
763+
# Combine two operations into one:
764+
# (((Remaining * x * A2 + B2) / C2) * x * A1 + B1) / C1
765+
# ((Remaining * (x*x) * (A2*A1) + (x*B2*A1+B1*C2)) / (C1*C2)
766+
# Therefore, combined operation can be represented as:
767+
# Anext = A2 * A1
768+
# Bnext = x * B2 * A1 + B1 * C2
769+
# Cnext = C1 * C2
770+
# xnext = x * x
771+
a1, b1, c1 = op1
772+
a2, b2, c2 = op2 || [[zero] * 4, [zero] * 4, BigDecimal(1)]
773+
[
774+
_bs_matrix_mult(a2, a1, 2, prec),
775+
_bs_weighted_sum(_bs_matrix_mult(b2, a1, 2, prec), xpow, b1, c2, prec),
776+
c1.mult(c2, prec),
777+
]
778+
end
779+
end
780+
_, sum_matrix, denominator = operations.first
781+
(sum_matrix[1] + f_a * (2 * a * sum_matrix[1] + sum_matrix[0])).div(denominator, prec)
685782
end
686783

687-
private_class_method def _erfc_asymptotic(x, prec) # :nodoc:
784+
# Calculates asymptotic expansion of erfc(x)*exp(x**2)*sqrt(pi)/2 with binary splitting method
785+
private_class_method def _erfc_exp2_asymptotic_binary_splitting(x, prec) # :nodoc:
688786
# Let f(x) = erfc(x)*sqrt(pi)*exp(x**2)/2
689787
# f(x) satisfies the following differential equation:
690788
# 2*x*f(x) = f'(x) + 1
@@ -697,21 +795,117 @@ def erfc(x, prec)
697795
# Using Stirling's approximation, we can simplify this condition to:
698796
# sqrt(2)/2 + k*log(k) - k - 2*k*log(x) < -prec*log(10)
699797
# and the left side is minimized when k = x**2.
700-
prec += BigDecimal.double_fig
701798
xf = x.to_f
702799
kmax = (1..(xf ** 2).floor).bsearch do |k|
703800
Math.log(2) / 2 + k * Math.log(k) - k - 2 * k * Math.log(xf) < -prec * Math.log(10)
704801
end
705802
return unless kmax
706803

707-
sum = BigDecimal(1)
708-
x2 = x.mult(x, prec)
709-
d = BigDecimal(1)
710-
(1..kmax).each do |k|
711-
d = d.div(x2, prec).mult(1 - 2 * k, prec).div(2, prec)
712-
sum = sum.add(d, prec)
804+
# Convert asymptotic expansion to nested form:
805+
# 1 + a/x + a*b/x/x + a*b*c/x/x/x + a*b*c/x/x/x*rest
806+
# = 1 + (a/x) * (1 + (b/x) * (1 + (c/x) * (1 + rest)))
807+
#
808+
# And calculate it with binary splitting:
809+
# (a1/d + b1/d * (a2/d + b2/d * (rest)))
810+
# = ((a1*d+b1*a2)/(d*d) + b1*b2/(d*denominator) * (rest)))
811+
denominator = x.mult(x, prec).mult(2, prec)
812+
fractions = (1..kmax).map do |k|
813+
[denominator, BigDecimal(1 - 2 * k)]
814+
end
815+
while fractions.size > 1
816+
fractions = fractions.each_slice(2).map do |fraction1, fraction2|
817+
a1, b1 = fraction1
818+
a2, b2 = fraction2 || [BigDecimal(0), denominator]
819+
[
820+
a1.mult(denominator, prec).add(b1.mult(a2, prec), prec),
821+
b1.mult(b2, prec),
822+
]
823+
end
824+
denominator = denominator.mult(denominator, prec)
825+
end
826+
sum = fractions[0][0].add(fractions[0][1], prec).div(denominator, prec)
827+
sum.div(x, prec) / 2
828+
end
829+
830+
# Calculates f(1/(a+x)) where f(x) = (sqrt(pi)/2) * exp(1/x**2) * erfc(1/x)
831+
# Parameter f_inva is f(1/a)
832+
private_class_method def _erfc_exp2_inv_inv_binary_splitting(x, a, f_inva, prec) # :nodoc:
833+
return f_inva if x.zero?
834+
835+
# Performs taylor expansion using f(1/(a+x)) = f(1/a - x/(a*(a+x)))
836+
837+
# f(x) satisfies the following differential equation:
838+
# (1/a+w)**3*f'(1/a+w) + 2*f(1/a+w) = 1/a + w
839+
# From the above equation, we can derive the following Taylor expansion of f around 1/a:
840+
# Coefficients: f(1/a + w) = c0 + c1*w + c2*w**2 + c3*w**3 + ...
841+
# Constraints:
842+
# (w**3 + 3*w**2/a + 3*w/a**2 + 1/a**3) * (c1 + 2*c2*w + 3*c3*w**2 + 4*c4*w**3 + ...)
843+
# + 2 * (c0 + c1*w + c2*w**2 + c3*w**3 + ...) = 1/a + w
844+
# Recurrence relations:
845+
# c0 = f(1/a)
846+
# c1 = a**2 - 2*c0*a**3
847+
# c2 = (a**3 - 3*c1*a - 2*c1*a**3) / 2
848+
# c3 = -(3*c1*a**2 + 6*c2*a + 2*c2*a**3) / 3
849+
# c(n) = -((n-3)*c(n-3)*a**3 + 3*(n-2)*c(n-2)*a**2 + 3*(n-1)*c(n-1)*a + 2*c(n-1)*a**3) / n
850+
851+
aa = a.mult(a, prec)
852+
aaa = aa.mult(a, prec)
853+
c0 = f_inva
854+
c1 = (aa - 2 * c0 * aaa).mult(1, prec)
855+
c2 = (aaa - 3 * c1 * a - 2 * c1 * aaa).div(2, prec)
856+
857+
# Estimate the number of steps needed to achieve the required precision
858+
low_prec = 16
859+
w = x.div(a.mult(a + x, low_prec), low_prec)
860+
wpow = w.mult(w, low_prec)
861+
cm3, cm2, cm1 = [c0, c1, c2].map {|v| v.mult(1, low_prec) }
862+
a_low, aa_low, aaa_low = [a, aa, aaa].map {|v| v.mult(1, low_prec) }
863+
step = (3..).find do |n|
864+
wpow = wpow.mult(w, low_prec)
865+
cn = -((n - 3) * cm3 * aaa_low + 3 * aa_low * (n - 2) * cm2 + 3 * a_low * (n - 1) * cm1 + 2 * cm1 * aaa_low).div(n, low_prec)
866+
cm3, cm2, cm1 = cm2, cm1, cn
867+
cn.mult(wpow, low_prec).exponent < -prec
868+
end
869+
870+
# Let M(n) be a 3x3 matrix that transforms (c(n),c(n+1),c(n+2)) to (c(n-1),c(n),c(n+1))
871+
# Mn = | 0 1 0 |
872+
# | 0 0 1 |
873+
# | -(n-3)*aaa/n -3*(n-2)*aa/n -2*aaa-3*(n-1)*a/n |
874+
# Vector(c6,c7,c8) = M6*M5*M4*M3*M2*M1 * Vector(c0,c1,c2)
875+
# Vector(c0+c1*y/z+c2*(y/z)**2+..., _, _) = (((... + I)*M3*y/z + I)*M2*y/z + I)*M1*y/z + I) * Vector(c2, c1, c0)
876+
# Perform binary splitting on this nested parenthesized calculation by using the following formula:
877+
# (((...)*A2*y/z + B2)/D2 * A1*y/z + B1)/D1 = (((...)*(A2*A1)*(y*y)/z + (B2*A1*y+z*D2*B1)) / (D1*D2*z)
878+
# where A_n, Bn are matrices and Dn are scalars
879+
880+
zero = BigDecimal(0)
881+
operations = (3..step + 2).map do |n|
882+
bign = BigDecimal(n)
883+
[
884+
[
885+
zero, bign, zero,
886+
zero, zero, bign,
887+
BigDecimal(-(n - 3) * aaa), -3 * (n - 2) * aa, -2 * aaa - 3 * (n - 1) * a
888+
],
889+
[bign, zero, zero, zero, bign, zero, zero, zero, bign],
890+
bign
891+
]
892+
end
893+
894+
z = a.mult(a + x, prec)
895+
while operations.size > 1
896+
y = y ? y.mult(y, prec) : -x.mult(1, prec)
897+
operations = operations.each_slice(2).map do |op1, op2|
898+
a1, b1, d1 = op1
899+
a2, b2, d2 = op2 || [[zero] * 9, [zero] * 9, BigDecimal(1)]
900+
[
901+
_bs_matrix_mult(a2, a1, 3, prec),
902+
_bs_weighted_sum(_bs_matrix_mult(b2, a1, 3, prec), y, b1, d2.mult(z, prec), prec),
903+
d1.mult(d2, prec).mult(z, prec),
904+
]
905+
end
713906
end
714-
sum.div(exp(x2, prec).mult(PI(prec).sqrt(prec), prec), prec).div(x, prec)
907+
_, sum_matrix, denominator = operations[0]
908+
(sum_matrix[0] * c0 + sum_matrix[1] * c1 + sum_matrix[2] * c2).div(denominator, prec)
715909
end
716910

717911
# call-seq:

test/bigdecimal/test_bigmath.rb

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -547,6 +547,15 @@ def test_erfc
547547
assert_converge_in_precision {|n| BigMath.erfc(BigDecimal(20.5), n) }
548548
end
549549

550+
def test_erf_erfc_consistency_large_prec
551+
[BigDecimal(34.5), 34 + BigDecimal(4).div(7, 1200)].each do |x|
552+
erf = BigMath.erf(x, 1200) # Calculated with taylor series of erf
553+
erfc = BigMath.erfc(x, 400) # Calculated with asymptotic expansion
554+
erfc2 = 1 - erf
555+
assert_equal(erfc, erfc2.mult(1, 400))
556+
end
557+
end
558+
550559
def test_gamma
551560
[-1.8, -0.7, 0.6, 1.5, 2.4].each do |x|
552561
assert_in_epsilon(Math.gamma(x), gamma(BigDecimal(x.to_s), N))

0 commit comments

Comments
 (0)