Skip to content

Commit dfe1b43

Browse files
committed
Minor approx root spedup
1 parent 75274eb commit dfe1b43

File tree

1 file changed

+12
-4
lines changed

1 file changed

+12
-4
lines changed

osmomath/decimal.go

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -302,7 +302,13 @@ func (d BigDec) AddMut(d2 BigDec) BigDec {
302302

303303
// subtraction
304304
func (d BigDec) Sub(d2 BigDec) BigDec {
305-
res := new(big.Int).Sub(d.i, d2.i)
305+
copy := d.Clone()
306+
copy.SubMut(d2)
307+
return copy
308+
}
309+
310+
func (d BigDec) SubMut(d2 BigDec) BigDec {
311+
res := d.i.Sub(d.i, d2.i)
306312

307313
if res.BitLen() > maxDecBitLen {
308314
panic("Int overflow")
@@ -555,7 +561,7 @@ func (d BigDec) ApproxRoot(root uint64) (guess BigDec, err error) {
555561
return absRoot.MulInt64(-1), err
556562
}
557563

558-
if root == 1 || d.IsZero() || d.Equal(OneBigDec()) {
564+
if root == 1 || d.IsZero() || d.Equal(oneBigDec) {
559565
return d, nil
560566
}
561567

@@ -572,7 +578,7 @@ func (d BigDec) ApproxRoot(root uint64) (guess BigDec, err error) {
572578
prev = SmallestBigDec()
573579
}
574580
delta = d.Quo(prev)
575-
delta = delta.Sub(guess)
581+
delta.SubMut(guess)
576582
delta = delta.QuoInt(rootInt)
577583

578584
guess = guess.Add(delta)
@@ -583,6 +589,7 @@ func (d BigDec) ApproxRoot(root uint64) (guess BigDec, err error) {
583589

584590
// ApproxSqrt is a wrapper around ApproxRoot for the common special case
585591
// of finding the square root of a number. It returns -(sqrt(abs(d)) if input is negative.
592+
// TODO: Optimize this to be faster just using native big int sqrt.
586593
func (d BigDec) ApproxSqrt() (BigDec, error) {
587594
return d.ApproxRoot(2)
588595
}
@@ -1271,6 +1278,7 @@ func (d BigDec) Power(power BigDec) BigDec {
12711278
if power.Abs().GT(maxSupportedExponent) {
12721279
panic(fmt.Sprintf("integer exponent %s is too large, max (%s)", power, maxSupportedExponent))
12731280
}
1281+
// TODO: Potentially expensive??
12741282
if power.IsInteger() {
12751283
return d.PowerInteger(power.TruncateInt().Uint64())
12761284
}
@@ -1280,7 +1288,7 @@ func (d BigDec) Power(power BigDec) BigDec {
12801288
if d.IsZero() {
12811289
return ZeroBigDec()
12821290
}
1283-
if d.LT(OneBigDec()) {
1291+
if d.LT(oneBigDec) {
12841292
panic(fmt.Sprintf("Power() is not supported for base < 1, base was (%s)", d))
12851293
}
12861294
if d.Equal(twoBigDec) {

0 commit comments

Comments
 (0)