From 013e52d4e9a51a5f90c7430b5848eaee91719280 Mon Sep 17 00:00:00 2001 From: Ilya Glukhov Date: Tue, 12 Oct 2021 03:17:36 +0300 Subject: [PATCH] Add Copy func (#123) * Add Copy method Co-authored-by: habuvo --- decimal.go | 17 ++++++++++++++--- decimal_test.go | 18 ++++++++++++++++++ 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/decimal.go b/decimal.go index acc8a9ba..9a80dc53 100644 --- a/decimal.go +++ b/decimal.go @@ -1755,7 +1755,7 @@ func (d Decimal) Sin() Decimal { sign = !sign j -= 4 } - z := d.Sub(y.Mul(PI4A)).Sub(y.Mul(PI4B)).Sub(y.Mul(PI4C)) // Extended precision modular arithmetic + z := d.Sub(y.Mul(PI4A)).Sub(y.Mul(PI4B)).Sub(y.Mul(PI4C)) // Extended precision modular arithmetic zz := z.Mul(z) if j == 1 || j == 2 { @@ -1842,12 +1842,12 @@ var _tanQ = [...]Decimal{ // Tan returns the tangent of the radian argument x. func (d Decimal) Tan() Decimal { - + PI4A := NewFromFloat(7.85398125648498535156e-1) // 0x3fe921fb40000000, Pi/4 split into three parts PI4B := NewFromFloat(3.77489470793079817668e-8) // 0x3e64442d00000000, PI4C := NewFromFloat(2.69515142907905952645e-15) // 0x3ce8469898cc5170, M4PI := NewFromFloat(1.273239544735162542821171882678754627704620361328125) // 4/pi - + if d.Equal(NewFromFloat(0.0)) { return d } @@ -1886,3 +1886,14 @@ func (d Decimal) Tan() Decimal { } return y } + +// Copy makes instance of d with same value and different pointer. +func (d Decimal) Copy() Decimal { + d.ensureInitialized() + return Decimal{ + value: &(*d.value), + exp: d.exp, + } +} + + diff --git a/decimal_test.go b/decimal_test.go index 25b664d4..686b8bbc 100644 --- a/decimal_test.go +++ b/decimal_test.go @@ -3288,3 +3288,21 @@ func ExampleNewFromFloat() { //0.123123123123123 //-10000000000000 } + +//For Copy +func TestCopy(t *testing.T) { + origin := New(1, 0) + cpy := origin.Copy() + + if cpy.Cmp(origin) != 0 { + t.Error("copy and origin not equal") + } + + //change value + cpy = cpy.Add(New(1, 0)) + + if cpy.Cmp(origin) == 0 { + t.Error("copy and origin are equal but expected not") + } + +}