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

Speedup log2 code #7106

Merged
merged 2 commits into from
Dec 13, 2023
Merged
Changes from 1 commit
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
21 changes: 13 additions & 8 deletions osmomath/decimal.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,11 @@ var (

// precisionFactors are used to adjust the scale of big.Int values to match the desired precision
precisionFactors = make(map[uint64]*big.Int)

zeroBigDec BigDec = ZeroBigDec()
oneBigDec BigDec = OneBigDec()
oneHalfBigDec BigDec = oneBigDec.Quo(twoBigDec)
negOneBigDec BigDec = oneBigDec.Neg()
)

// Decimal errors
Expand Down Expand Up @@ -1037,9 +1042,9 @@ func DecApproxEq(t *testing.T, d1 BigDec, d2 BigDec, tol BigDec) (*testing.T, bo
func (x BigDec) LogBase2() BigDec {
// create a new decimal to avoid mutating
// the receiver's int buffer.
xCopy := ZeroBigDec()
xCopy := BigDec{}
xCopy.i = new(big.Int).Set(x.i)
if xCopy.LTE(ZeroBigDec()) {
if xCopy.LTE(zeroBigDec) {
panic(fmt.Sprintf("log is not defined at <= 0, given (%s)", xCopy))
}

Expand All @@ -1049,18 +1054,18 @@ func (x BigDec) LogBase2() BigDec {
y := ZeroBigDec()

// repeat until: x >= 1.
for xCopy.LT(OneBigDec()) {
for xCopy.LT(oneBigDec) {
xCopy.i.Lsh(xCopy.i, 1)
y = y.Sub(OneBigDec())
y.AddMut(negOneBigDec)
}

// repeat until: x < 2.
for xCopy.GTE(twoBigDec) {
xCopy.i.Rsh(xCopy.i, 1)
y = y.Add(OneBigDec())
y.AddMut(oneBigDec)
}

b := OneBigDec().Quo(twoBigDec)
b := oneHalfBigDec.Clone()

// N.B. At this point x is a positive real number representing
// mantissa of the log. We estimate it using the following
Expand All @@ -1069,10 +1074,10 @@ func (x BigDec) LogBase2() BigDec {
// This has shown precision of 32 digits relative
// to Wolfram Alpha in tests.
for i := 0; i < maxLog2Iterations; i++ {
xCopy = xCopy.Mul(xCopy)
xCopy.MulMut(xCopy)
if xCopy.GTE(twoBigDec) {
xCopy.i.Rsh(xCopy.i, 1)
y = y.Add(b)
y.AddMut(b)
}
b.i.Rsh(b.i, 1)
}
Expand Down