Skip to content

Commit

Permalink
Decimal: use 0.5 multiply instead of Quo 2 in Sqrt
Browse files Browse the repository at this point in the history
  • Loading branch information
db47h committed May 20, 2020
1 parent a7dffd9 commit 8960865
Showing 1 changed file with 7 additions and 7 deletions.
14 changes: 7 additions & 7 deletions decimal_sqrt.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ package decimal
import "math"

var (
three = NewDecimal(3.0)
two = NewDecimal(2.0)
oneHalf = NewDecimal(0.5) // will be exact
three = NewDecimal(3.0)
)

// Sqrt sets z to the rounded square root of x, and returns it.
Expand Down Expand Up @@ -85,11 +85,11 @@ func (z *Decimal) Sqrt(x *Decimal) *Decimal {
sqi.prec *= 2
u.prec = sqi.prec
v.prec = sqi.prec
u.Mul(sqi, sqi) // u = sqi²
u.Mul(x, u) // = x.sqi²
v.Sub(three, u) // v = 3 - x.sqi²
u.Mul(sqi, v) // u = sqi(3 - x.sqi²)
sqi.Quo(u, two) // sqi = ½sqi(3 - x.sqi²)
u.Mul(sqi, sqi) // u = sqi²
u.Mul(x, u) // = x.sqi²
v.Sub(three, u) // v = 3 - x.sqi²
u.Mul(sqi, v) // u = sqi(3 - x.sqi²)
sqi.Mul(u, oneHalf) // sqi = ½sqi(3 - x.sqi²)
}
// sqi = 1/√x

Expand Down

0 comments on commit 8960865

Please sign in to comment.