Skip to content

Instantly share code, notes, and snippets.

@mwhooker
Last active August 15, 2019 23:47
Show Gist options
  • Save mwhooker/c4f8d8811e91c6b88096ea85e7ac23d2 to your computer and use it in GitHub Desktop.
Save mwhooker/c4f8d8811e91c6b88096ea85e7ac23d2 to your computer and use it in GitHub Desktop.
decimal comparison
package main
import (
"fmt"
"math/big"
"github.com/cockroachdb/apd"
ericl "github.com/ericlagergren/decimal"
shopspring "github.com/shopspring/decimal"
)
const ONE, DENOM = 1.0, 744.0
func main() {
shopspring.DivisionPrecision = 100
fmt.Printf("Showing results for (%f / %f) * %f:\n", ONE, DENOM, DENOM)
fmt.Println("shopspring:")
testShopspring()
fmt.Println("ericl:")
testEricl()
fmt.Println("cockroach:")
testCockroach()
fmt.Println("math/big:")
testBig()
fmt.Println("\nbig mul:")
testBigMul()
fmt.Println("cockroach mul:")
testCockroachMul()
fmt.Println("ericl mul:")
testEriclMul()
}
func testEricl() {
a := ericl.WithPrecision(100)
b := ericl.WithPrecision(100)
y := ericl.WithPrecision(100)
z := ericl.WithPrecision(100)
a.SetFloat64(ONE)
b.SetFloat64(DENOM)
y.Quo(a, b)
z.Mul(y, b)
fmt.Println(z.Reduce().String())
}
func testCockroach() {
c := &apd.Context{
Precision: 100,
Rounding: apd.RoundHalfEven,
MaxExponent: apd.MaxExponent,
MinExponent: apd.MinExponent,
}
a := apd.New(ONE, 0)
b := apd.New(DENOM, 0)
var x, y, reduced apd.Decimal
c1, e1 := c.Quo(&x, a, b)
c2, e2 := c.Mul(&y, &x, b)
reduced.Reduce(&y)
fmt.Println(c1, e1, c2, e2)
fmt.Println(reduced.String())
}
func testCockroachMul() {
a, err := new(apd.Decimal).SetFloat64(1.1)
if err != nil {
panic(err)
}
b := apd.New(3, 0)
var x apd.Decimal
apd.BaseContext.Mul(&x, a, b)
fmt.Printf("%.25f\n", &x)
}
func testBigMul() {
var a, b, z big.Float
a.SetFloat64(1.1)
b.SetFloat64(3)
z.Mul(&a, &b)
fmt.Printf("%.25f\n", &z)
}
func testEriclMul() {
a := ericl.WithPrecision(1000)
b := ericl.WithPrecision(1000)
z := ericl.WithPrecision(1000)
a.SetString("1.1")
b.SetFloat64(3)
z.Mul(a, b)
fmt.Println(z.Reduce())
}
func testBig() {
var y, z big.Float
a, _, _ := big.ParseFloat("1.1", 10, 1000, big.ToNearestEven)
b, _, _ := big.ParseFloat("3.0", 10, 1000, big.ToNearestEven)
y.Quo(a, b)
z.Mul(&y, b)
fmt.Println(z.String())
}
func testShopspring() {
a := shopspring.New(ONE, 0)
b := shopspring.New(DENOM, 0)
fmt.Println(a.Div(b).Mul(b).String())
}
Showing results for (1.000000 / 744.000000) * 744.000000:
shopspring:
0.999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999984
ericl:
1
cockroach:
inexact, rounded <nil> inexact, rounded <nil>
1
math/big:
1.1
big mul:
3.3000000000000002664535259
cockroach mul:
3.3
ericl mul:
3.3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment