Compare commits

...

5 commits

Author SHA1 Message Date
Leo
066a525084
Merge aa070c4ec8 into 0e69d5cd53 2024-04-06 00:04:50 +08:00
Mateusz Woś
0e69d5cd53
Run CI on both push to origin branches and pull requests (#360) 2024-04-04 16:35:31 +02:00
Philip Dubé
bf7794e1a8
Optimize NumDigits method (#356) 2024-04-04 16:14:38 +02:00
Leonardo
aa070c4ec8 make Sqrt a method of Decimal; add unit tests (1 failing) 2021-03-27 13:52:30 -07:00
Leonardo Cicconi
a68916bc93 added Sqrt and SqrtRound functions 2021-03-25 17:42:49 -07:00
4 changed files with 153 additions and 11 deletions

View file

@ -1,5 +1,9 @@
name: ci name: ci
on: [push] on:
push:
branches:
- master
pull_request:
jobs: jobs:
ci-job: ci-job:
runs-on: ubuntu-latest runs-on: ubuntu-latest

View file

@ -19,6 +19,7 @@ package decimal
import ( import (
"database/sql/driver" "database/sql/driver"
"encoding/binary" "encoding/binary"
"errors"
"fmt" "fmt"
"math" "math"
"math/big" "math/big"
@ -1224,14 +1225,33 @@ func (d Decimal) Ln(precision int32) (Decimal, error) {
} }
// NumDigits returns the number of digits of the decimal coefficient (d.Value) // NumDigits returns the number of digits of the decimal coefficient (d.Value)
// Note: Current implementation is extremely slow for large decimals and/or decimals with large fractional part
func (d Decimal) NumDigits() int { func (d Decimal) NumDigits() int {
d.ensureInitialized() if d.value == nil {
// Note(mwoss): It can be optimized, unnecessary cast of big.Int to string return 1
if d.IsNegative() {
return len(d.value.String()) - 1
} }
return len(d.value.String())
if d.value.IsInt64() {
i64 := d.value.Int64()
// restrict fast path to integers with exact conversion to float64
if i64 <= (1<<53) && i64 >= -(1<<53) {
if i64 == 0 {
return 1
}
return int(math.Log10(math.Abs(float64(i64)))) + 1
}
}
estimatedNumDigits := int(float64(d.value.BitLen()) / math.Log2(10))
// estimatedNumDigits (lg10) may be off by 1, need to verify
digitsBigInt := big.NewInt(int64(estimatedNumDigits))
errorCorrectionUnit := digitsBigInt.Exp(tenInt, digitsBigInt, nil)
if d.value.CmpAbs(errorCorrectionUnit) >= 0 {
return estimatedNumDigits + 1
}
return estimatedNumDigits
} }
// IsInteger returns true when decimal can be represented as an integer value, otherwise, it returns false. // IsInteger returns true when decimal can be represented as an integer value, otherwise, it returns false.
@ -2303,3 +2323,59 @@ func (d Decimal) Tan() Decimal {
} }
return y return y
} }
// More math
// Sqrt returns the square root of d, accurate to DivisionPrecision decimal places.
// Sqrt is only valid for non-negative numbers; it will return an error otherwise.
func (d Decimal) Sqrt() (Decimal, error) {
s, _, err := d.SqrtRound(int32(DivisionPrecision))
return s, err
}
// ErrImaginaryResult indicates an operation that would produce an imaginary result.
var ErrImaginaryResult = errors.New("The result of this operation is imaginary.")
// SqrtMaxIter sets a limit for number of iterations for the Sqrt function
const SqrtMaxIter = 1000000
// SqrtRound returns the square root of d, accurate to precision decimal places.
// The bool precise returns whether the precision was achieved.
// SqrtRound is only valid for non-negative numbers; it will return an error otherwise.
func (d Decimal) SqrtRound(precision int32) (Decimal, bool, error) {
var (
maxError = New(1, -precision)
one = NewFromFloat(1)
lo, hi Decimal
)
// Handle cases where d < 0, d = 0, 0 < d < 1, and d > 1
if d.GreaterThanOrEqual(one) {
lo = Zero
hi = d
} else if d.Equal(one) {
return one, true, nil
} else if d.LessThan(Zero) {
return Zero, false, ErrImaginaryResult
} else if d.Equal(Zero) {
return Zero, true, nil
} else {
// d is between 0 and 1. Therefore, 0 < d < Sqrt(d) < 1.
lo = d
hi = one
}
var mid Decimal
for i := 0; i < SqrtMaxIter; i++ {
mid = lo.Add(hi).Div(New(2, 0)) //mid = (lo+hi)/2;
if mid.Mul(mid).Sub(d).Abs().LessThan(maxError) {
return mid, true, nil
}
if mid.Mul(mid).GreaterThan(d) {
hi = mid
} else {
lo = mid
}
}
return mid, false, nil
}

View file

@ -121,6 +121,34 @@ func BenchmarkDecimal_RoundCash_Five(b *testing.B) {
} }
} }
func numDigits(b *testing.B, want int, val Decimal) {
b.Helper()
for i := 0; i < b.N; i++ {
if have := val.NumDigits(); have != want {
b.Fatalf("\nHave: %d\nWant: %d", have, want)
}
}
}
func BenchmarkDecimal_NumDigits10(b *testing.B) {
numDigits(b, 10, New(3478512345, -3))
}
func BenchmarkDecimal_NumDigits100(b *testing.B) {
s := make([]byte, 102)
for i := range s {
s[i] = byte('0' + i%10)
}
s[0] = '-'
s[100] = '.'
d, err := NewFromString(string(s))
if err != nil {
b.Log(d)
b.Error(err)
}
numDigits(b, 100, d)
}
func Benchmark_Cmp(b *testing.B) { func Benchmark_Cmp(b *testing.B) {
decimals := DecimalSlice([]Decimal{}) decimals := DecimalSlice([]Decimal{})
for i := 0; i < 1000000; i++ { for i := 0; i < 1000000; i++ {
@ -132,7 +160,7 @@ func Benchmark_Cmp(b *testing.B) {
} }
} }
func Benchmark_decimal_Decimal_Add_different_precision(b *testing.B) { func BenchmarkDecimal_Add_different_precision(b *testing.B) {
d1 := NewFromFloat(1000.123) d1 := NewFromFloat(1000.123)
d2 := NewFromFloat(500).Mul(NewFromFloat(0.12)) d2 := NewFromFloat(500).Mul(NewFromFloat(0.12))
@ -143,7 +171,7 @@ func Benchmark_decimal_Decimal_Add_different_precision(b *testing.B) {
} }
} }
func Benchmark_decimal_Decimal_Sub_different_precision(b *testing.B) { func BenchmarkDecimal_Sub_different_precision(b *testing.B) {
d1 := NewFromFloat(1000.123) d1 := NewFromFloat(1000.123)
d2 := NewFromFloat(500).Mul(NewFromFloat(0.12)) d2 := NewFromFloat(500).Mul(NewFromFloat(0.12))
@ -154,7 +182,7 @@ func Benchmark_decimal_Decimal_Sub_different_precision(b *testing.B) {
} }
} }
func Benchmark_decimal_Decimal_Add_same_precision(b *testing.B) { func BenchmarkDecimal_Add_same_precision(b *testing.B) {
d1 := NewFromFloat(1000.123) d1 := NewFromFloat(1000.123)
d2 := NewFromFloat(500.123) d2 := NewFromFloat(500.123)
@ -165,7 +193,7 @@ func Benchmark_decimal_Decimal_Add_same_precision(b *testing.B) {
} }
} }
func Benchmark_decimal_Decimal_Sub_same_precision(b *testing.B) { func BenchmarkDecimal_Sub_same_precision(b *testing.B) {
d1 := NewFromFloat(1000.123) d1 := NewFromFloat(1000.123)
d2 := NewFromFloat(500.123) d2 := NewFromFloat(500.123)

View file

@ -3460,6 +3460,40 @@ func TestAvg(t *testing.T) {
} }
} }
func TestSqrtRound(t *testing.T) {
i := NewFromFloat(-1)
if _, err := i.Sqrt(); err != ErrImaginaryResult {
t.Errorf("Square root of -1 should produce error")
}
var vals = map[string]string{
// value : Sqrt(value)
"0.0": "0.0",
"0.002342": "0.0483942145302514",
"1.0": "1.0",
"3.0": "1.7320508075688773",
"4.0": "2.0",
"4.5": "2.1213203435596426",
"3289854.0": "1813.7954680724064485",
}
for val, expected := range vals {
v, err := NewFromString(val)
if err != nil {
t.Errorf("error parsing test value into Decimal")
}
e, err := NewFromString(expected)
if err != nil {
t.Errorf("error parsing test expected value into Decimal")
}
if sqrt, err := v.Sqrt(); err != nil || !sqrt.Equal(e) {
t.Errorf("Square root of %s should be %s, not %s (error: %s)", v, e, sqrt, err)
}
}
}
func TestRoundBankAnomaly(t *testing.T) { func TestRoundBankAnomaly(t *testing.T) {
a := New(25, -1) a := New(25, -1)
b := New(250, -2) b := New(250, -2)