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

Create sqrt.go #111

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
32 changes: 32 additions & 0 deletions sqrt.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package decimal

const SqrtMaxIter 100000

// Sqrt returns the square root of d, the result will have
// DivisionPrecision digits after the decimal point.
func (d Decimal) Sqrt() Decimal {
s, _ := d.SqrtRound(int32(decimal.DivisionPrecision))
return s
}

// SqrtRound returns the square root of d, the result will have
// precision digits after the decimal point. The bool precise returns whether the precision was reached
func (d Decimal) SqrtRound(precision int32) (Decimal, bool) {
cutoff := New(1, -precision)
lo := Zero
hi := d
var mid Decimal
for i := 0; i < SqrtMaxIter; i++ {
//mid = (lo+hi)/2;
mid = lo.Add(hi).DivRound(New(2, 0), precision)
if mid.Mul(mid).Sub(d).Abs().LessThan(cutoff) {
return mid, true
}
if mid.Mul(mid).GreaterThan(d) {
hi = mid
} else {
lo = mid
}
}
return mid, false
}