Skip to content

Commit

Permalink
Adjust Ln method to prevent infinity iteration loops (shopspring#357)
Browse files Browse the repository at this point in the history
* Adjust Ln method to prevent infinity iteration loops
* Add test case for infinity loop
  • Loading branch information
mwoss authored and epelc committed Apr 7, 2024
1 parent b50c98b commit d12a24b
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
13 changes: 12 additions & 1 deletion decimal.go
Original file line number Diff line number Diff line change
Expand Up @@ -911,7 +911,10 @@ func (d Decimal) Ln(precision int32) (Decimal, error) {
// Halley's Iteration.
// Calculating n-th term of formula: a_(n+1) = a_n - 2 * (exp(a_n) - z) / (exp(a_n) + z),
// until the difference between current and next term is smaller than epsilon
for {
var prevStep Decimal
maxIters := calcPrecision*2 + 10

for i := int32(0); i < maxIters; i++ {
// exp(a_n)
comp3, _ = comp1.ExpTaylor(calcPrecision)
// exp(a_n) - z
Expand All @@ -925,9 +928,17 @@ func (d Decimal) Ln(precision int32) (Decimal, error) {
// comp1 = a_(n+1) = a_n - 2 * (exp(a_n) - z) / (exp(a_n) + z)
comp1 = comp1.Sub(comp3)

if prevStep.Add(comp3).IsZero() {
// If iteration steps oscillate we should return early and prevent an infinity loop
// NOTE(mwoss): This should be quite a rare case, returning error is not necessary
break
}

if comp3.Abs().Cmp(epsilon) <= 0 {
break
}

prevStep = comp3
}
}

Expand Down
1 change: 1 addition & 0 deletions decimal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2568,6 +2568,7 @@ func TestDecimal_Ln(t *testing.T) {
{"839101.0351094726488848490572028502", 50, "13.64008640145229044389152437468283605382056561604272"},
{"5023583755703750094849.03519358513093500275017501750602739169823", 25, "49.9684305274348922267409953"},
{"5023583755703750094849.03519358513093500275017501750602739169823", -1, "50.0"},
{"66.12", 18, "4.191471272952823429"},
} {
d, _ := NewFromString(testCase.Dec)
expected, _ := NewFromString(testCase.Expected)
Expand Down

0 comments on commit d12a24b

Please sign in to comment.