Compare commits

...

3 commits

Author SHA1 Message Date
Jim McDonald
a1bed2f5fe
Merge c31da0254a into 2b68c56fe0 2024-04-02 10:38:28 +08:00
Mateusz Woś
2b68c56fe0
Adjust Ln method to prevent infinity iteration loops (#357)
* Adjust Ln method to prevent infinity iteration loops
* Add test case for infinity loop
2024-04-01 22:02:25 +02:00
Jim McDonald
c31da0254a
Add Format() 2022-04-11 17:45:30 +01:00
2 changed files with 126 additions and 48 deletions

View file

@ -133,7 +133,6 @@ func NewFromBigInt(value *big.Int, exp int32) Decimal {
// d2 := NewFromBigRat(big.NewRat(4, 5), 1) // output: "0.8" // d2 := NewFromBigRat(big.NewRat(4, 5), 1) // output: "0.8"
// d3 := NewFromBigRat(big.NewRat(1000, 3), 3) // output: "333.333" // d3 := NewFromBigRat(big.NewRat(1000, 3), 3) // output: "333.333"
// d4 := NewFromBigRat(big.NewRat(2, 7), 4) // output: "0.2857" // d4 := NewFromBigRat(big.NewRat(2, 7), 4) // output: "0.2857"
//
func NewFromBigRat(value *big.Rat, precision int32) Decimal { func NewFromBigRat(value *big.Rat, precision int32) Decimal {
return Decimal{ return Decimal{
value: new(big.Int).Set(value.Num()), value: new(big.Int).Set(value.Num()),
@ -920,7 +919,10 @@ func (d Decimal) Ln(precision int32) (Decimal, error) {
// Halley's Iteration. // Halley's Iteration.
// Calculating n-th term of formula: a_(n+1) = a_n - 2 * (exp(a_n) - z) / (exp(a_n) + z), // Calculating n-th term of formula: a_(n+1) = a_n - 2 * (exp(a_n) - z) / (exp(a_n) + z),
// until the difference between current and next term is smaller than epsilon // until the difference between current and next term is smaller than epsilon
for { var prevStep Decimal
maxIters := calcPrecision*2 + 10
for i := int32(0); i < maxIters; i++ {
// exp(a_n) // exp(a_n)
comp3, _ = comp1.ExpTaylor(calcPrecision) comp3, _ = comp1.ExpTaylor(calcPrecision)
// exp(a_n) - z // exp(a_n) - z
@ -934,9 +936,17 @@ func (d Decimal) Ln(precision int32) (Decimal, error) {
// comp1 = a_(n+1) = a_n - 2 * (exp(a_n) - z) / (exp(a_n) + z) // comp1 = a_(n+1) = a_n - 2 * (exp(a_n) - z) / (exp(a_n) + z)
comp1 = comp1.Sub(comp3) comp1 = comp1.Sub(comp3)
if prevStep.Add(comp3).IsZero() {
// If iteration steps oscillate we should return early and prevent an infinity loop
// NOTE(mwoss): This should be quite a rare case, returning error is not necessary
break
}
if comp3.Abs().Cmp(epsilon) <= 0 { if comp3.Abs().Cmp(epsilon) <= 0 {
break break
} }
prevStep = comp3
} }
} }
@ -1165,6 +1175,73 @@ func (d Decimal) String() string {
return d.string(true) return d.string(true)
} }
// Format formats a decimal.
// thousandsSeparator can be empty, in which case the integer value will be displayed without separation.
// if decimalSeparator is empty and the value is a decimal this will panic.
func (d Decimal) Format(thousandsSeparator string, decimalSeparator string, trimTrailingZeros bool) string {
if d.exp >= 0 {
d = d.rescale(0)
}
abs := new(big.Int).Abs(d.value)
str := abs.String()
var intPart, fractionalPart string
// NOTE(vadim): this cast to int will cause bugs if d.exp == INT_MIN
// and you are on a 32-bit machine. Won't fix this super-edge case.
dExpInt := int(d.exp)
if len(str) > -dExpInt {
intPart = str[:len(str)+dExpInt]
fractionalPart = str[len(str)+dExpInt:]
} else {
intPart = "0"
num0s := -dExpInt - len(str)
fractionalPart = strings.Repeat("0", num0s) + str
}
if thousandsSeparator != "" {
parts := 1 + (len(intPart)-1)/3
if parts > 1 {
intParts := make([]string, 1+(len(intPart)-1)/3)
offset := len(intPart) - (len(intParts)-1)*3
for i := 0; i < len(intParts); i++ {
if i == 0 {
intParts[i] = intPart[0:offset]
} else {
intParts[i] = intPart[(i-1)*3+offset : i*3+offset]
}
}
intPart = strings.Join(intParts, thousandsSeparator)
}
}
if trimTrailingZeros {
i := len(fractionalPart) - 1
for ; i >= 0; i-- {
if fractionalPart[i] != '0' {
break
}
}
fractionalPart = fractionalPart[:i+1]
}
if fractionalPart != "" && decimalSeparator == "" {
panic("no decimal separator for non-integer")
}
number := intPart
if len(fractionalPart) > 0 {
number += decimalSeparator + fractionalPart
}
if d.value.Sign() < 0 {
return "-" + number
}
return number
}
// StringFixed returns a rounded fixed-point string with places digits after // StringFixed returns a rounded fixed-point string with places digits after
// the decimal point. // the decimal point.
// //
@ -1595,48 +1672,7 @@ func (d Decimal) StringScaled(exp int32) string {
} }
func (d Decimal) string(trimTrailingZeros bool) string { func (d Decimal) string(trimTrailingZeros bool) string {
if d.exp >= 0 { return d.Format("", ".", trimTrailingZeros)
return d.rescale(0).value.String()
}
abs := new(big.Int).Abs(d.value)
str := abs.String()
var intPart, fractionalPart string
// NOTE(vadim): this cast to int will cause bugs if d.exp == INT_MIN
// and you are on a 32-bit machine. Won't fix this super-edge case.
dExpInt := int(d.exp)
if len(str) > -dExpInt {
intPart = str[:len(str)+dExpInt]
fractionalPart = str[len(str)+dExpInt:]
} else {
intPart = "0"
num0s := -dExpInt - len(str)
fractionalPart = strings.Repeat("0", num0s) + str
}
if trimTrailingZeros {
i := len(fractionalPart) - 1
for ; i >= 0; i-- {
if fractionalPart[i] != '0' {
break
}
}
fractionalPart = fractionalPart[:i+1]
}
number := intPart
if len(fractionalPart) > 0 {
number += "." + fractionalPart
}
if d.value.Sign() < 0 {
return "-" + number
}
return number
} }
func (d *Decimal) ensureInitialized() { func (d *Decimal) ensureInitialized() {

View file

@ -1513,6 +1513,47 @@ func TestDecimal_RoundDownAndStringFixed(t *testing.T) {
} }
} }
func TestDecimal_Format(t *testing.T) {
type testData struct {
input string
thousandsSeparator string
decimalSeparator string
trimTrailingZeros bool
expected string
}
tests := []testData{
{"0", ",", ".", false, "0"},
{"0", ",", ".", true, "0"},
{"999", ",", ".", true, "999"},
{"1000", ",", ".", true, "1,000"},
{"123", ",", ".", true, "123"},
{"1234", ",", ".", true, "1,234"},
{"12345.67", "", ".", true, "12345.67"},
{"12345.00", ",", ".", true, "12,345"},
{"12345.00", ",", ".", false, "12,345.00"},
{"123456.00", ",", ".", false, "123,456.00"},
{"1234567.00", ",", ".", false, "1,234,567.00"},
{"1234567.00", ".", ",", false, "1.234.567,00"},
{"1234567.00", "_", ".", true, "1_234_567"},
{"-12.00", "_", ".", true, "-12"},
{"-123.00", "_", ".", true, "-123"},
{"-1234.00", "_", ".", true, "-1_234"},
}
for _, test := range tests {
d, err := NewFromString(test.input)
if err != nil {
panic(err)
}
got := d.Format(test.thousandsSeparator, test.decimalSeparator, test.trimTrailingZeros)
if got != test.expected {
t.Errorf("Format %s got %s, expected %s",
d, got, test.expected)
}
}
}
func TestDecimal_BankRoundAndStringFixed(t *testing.T) { func TestDecimal_BankRoundAndStringFixed(t *testing.T) {
type testData struct { type testData struct {
input string input string
@ -2822,6 +2863,7 @@ func TestDecimal_Ln(t *testing.T) {
{"839101.0351094726488848490572028502", 50, "13.64008640145229044389152437468283605382056561604272"}, {"839101.0351094726488848490572028502", 50, "13.64008640145229044389152437468283605382056561604272"},
{"5023583755703750094849.03519358513093500275017501750602739169823", 25, "49.9684305274348922267409953"}, {"5023583755703750094849.03519358513093500275017501750602739169823", 25, "49.9684305274348922267409953"},
{"5023583755703750094849.03519358513093500275017501750602739169823", -1, "50.0"}, {"5023583755703750094849.03519358513093500275017501750602739169823", -1, "50.0"},
{"66.12", 18, "4.191471272952823429"},
} { } {
d, _ := NewFromString(testCase.Dec) d, _ := NewFromString(testCase.Dec)
expected, _ := NewFromString(testCase.Expected) expected, _ := NewFromString(testCase.Expected)