Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(math):refact ApproxRoot for readality #22263

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 14 additions & 6 deletions math/dec.go
Original file line number Diff line number Diff line change
Expand Up @@ -467,33 +467,41 @@ func (d LegacyDec) ApproxRoot(root uint64) (guess LegacyDec, err error) {
}
}()

if root == 0 {
// Return 1 as root 0 of any number is considered 1.
return LegacyOneDec(), nil
}

if d.IsNegative() {
absRoot, err := d.Neg().ApproxRoot(root)
return absRoot.NegMut(), err
}

// One decimal, that we invalidate later. Helps us save a heap allocation.
// Direct return for base cases: d^1 = d or when d is 0 or 1.
scratchOneDec := LegacyOneDec()
if root == 1 || d.IsZero() || d.Equal(scratchOneDec) {
return d, nil
}

if root == 0 {
return scratchOneDec, nil
}

guess, delta := scratchOneDec, LegacyOneDec()

for iter := 0; iter < maxApproxRootIterations && delta.Abs().GT(smallestDec); iter++ {
for iter := 0; iter < maxApproxRootIterations; iter++ {
prev := guess.Power(root - 1)
if prev.IsZero() {
prev = smallestDec
}

// Compute delta = (d/prev - guess) / root
delta.Set(d).QuoMut(prev)
delta.SubMut(guess)
delta.QuoInt64Mut(int64(root))

guess.AddMut(delta)

// Stop when delta is small enough
if delta.Abs().LTE(smallestDec) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍 more readable

break
}
}

return guess, nil
Expand Down
Loading