Skip to content

Commit

Permalink
context: rename round() to set() to match decimal's API
Browse files Browse the repository at this point in the history
  • Loading branch information
db47h committed Jun 6, 2020
1 parent ab4d78a commit 305608a
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 10 deletions.
4 changes: 2 additions & 2 deletions context/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -166,9 +166,9 @@ func (c *Context) Err() (err error) {
return
}

// Round sets z's to the value of x and returns z rounded using c's precision
// Set sets z's to the value of x and returns z rounded using c's precision
// and rounding mode.
func (c *Context) Round(z, x *decimal.Decimal) *decimal.Decimal {
func (c *Context) Set(z, x *decimal.Decimal) *decimal.Decimal {
if handleNaNs {
if c.err != nil {
return z
Expand Down
34 changes: 26 additions & 8 deletions context/context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package context
import (
"errors"
"math"
"strconv"
"testing"

"github.com/db47h/decimal"
Expand All @@ -28,42 +29,59 @@ var (
thirtyTwo = new(decimal.Decimal).SetPrec(9).SetUint64(32)
)

func computePi(prec uint) *decimal.Decimal {
func computePi(z *decimal.Decimal) *decimal.Decimal {
var (
prec = z.Prec()
c = New(uint(math.Ceil(float64(prec)*1.1))+1, decimal.ToNearestEven)
lastS = c.New()
lastZ = c.New()
t = c.NewUint64(3)
s = c.NewUint64(3)
n = c.NewUint64(1)
na = c.New()
d = c.New()
da = c.NewUint64(24)
tmp = c.New()
)
for s.Cmp(lastS) != 0 {
lastS.Copy(s)
m := z.Mode()
z.SetMode(c.Mode()).SetPrec(c.Prec()).SetUint64(3)

for z.Cmp(lastZ) != 0 {
lastZ.Copy(z)
c.Add(n, n, na)
c.Add(na, na, eight)
c.Add(d, d, da)
c.Add(da, da, thirtyTwo)
c.Mul(tmp, t, n)
c.Quo(t, tmp, d)
c.Add(s, s, t)
c.Add(z, z, t)
}
return s.SetMode(decimal.ToNearestEven).SetPrec(prec)
return z.SetPrec(prec).SetMode(m)
}

func TestDecimalPi(t *testing.T) {
var zero decimal.Decimal
pi, _ := new(decimal.Decimal).SetPrec(uint(len(pi) - 1)).SetString(pi)
var got decimal.Decimal
for p := uint(1); p <= 100; p++ {
want := new(decimal.Decimal).SetPrec(p).Set(pi)
got := computePi(p)
got.Set(&zero).SetPrec(p)
computePi(&got)
if got.Cmp(want) != 0 {
t.Errorf("prec %d:\n\tgot %v\n\twant %v", p, got, want)
}
}
}

func BenchmarkPi(b *testing.B) {
for _, prec := range []uint{19, 34, 78, 150} {
b.Run(strconv.Itoa(int(prec)), func(b *testing.B) {
z := new(decimal.Decimal).SetPrec(prec)
for i := 0; i < b.N; i++ {
computePi(z)
}
})
}
}

var pi = "3." +
"14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651" +
"32823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461" +
Expand Down

0 comments on commit 305608a

Please sign in to comment.