diff --git a/src/math/big/float.go b/src/math/big/float.go index 015f1645b6..60e9a2d46d 100644 --- a/src/math/big/float.go +++ b/src/math/big/float.go @@ -203,6 +203,8 @@ func (x *Float) Sign() int { // It returns mant and exp satisfying x == mant × 2**exp, with // the absolute value of mant satisfying 0.5 <= |mant| < 1.0. // mant has the same precision and rounding mode as x. +// If a non-nil *Float argument z is provided it is used to +// store the result mant; otherwise a new Float is allocated. // // Special cases are: // @@ -210,11 +212,14 @@ func (x *Float) Sign() int { // (±Inf).MantExp() = ±Inf, 0 // // MantExp does not modify x; the result mant is a new Float. -func (x *Float) MantExp() (mant *Float, exp int) { - mant = new(Float).Copy(x) +func (x *Float) MantExp(z *Float) (mant *Float, exp int) { + if z == nil { + z = new(Float) + } + mant = z.Copy(x) if x.exp != infExp { - mant.exp = 0 exp = int(x.exp) + mant.exp = 0 // after reading x.exp (x and mant may be aliases) } return } diff --git a/src/math/big/float_test.go b/src/math/big/float_test.go index 00bb309908..f7c243e71a 100644 --- a/src/math/big/float_test.go +++ b/src/math/big/float_test.go @@ -147,13 +147,24 @@ func TestFloatMantExp(t *testing.T) { } { x := makeFloat(test.x) frac := makeFloat(test.frac) - f, e := x.MantExp() + f, e := x.MantExp(nil) if !feq(f, frac) || e != test.exp { t.Errorf("%s.MantExp() = %s, %d; want %s, %d", test.x, f.Format('g', 10), e, test.frac, test.exp) } } } +func TestFloatMantExpAliasing(t *testing.T) { + x := makeFloat("0.5p10") + z := new(Float) + if m, _ := x.MantExp(z); m != z { + t.Fatalf("MantExp didn't use supplied *Float") + } + if _, e := x.MantExp(x); e != 10 { + t.Fatalf("MantExp aliasing error: got %d; want 10", e) + } +} + func TestFloatSetMantExp(t *testing.T) { for _, test := range []struct { frac string @@ -185,7 +196,7 @@ func TestFloatSetMantExp(t *testing.T) { t.Errorf("SetMantExp(%s, %d) = %s; want %s", test.frac, test.exp, z.Format('g', 10), test.z) } // test inverse property - if z.SetMantExp(want.MantExp()).Cmp(want) != 0 { + if z.SetMantExp(want.MantExp(nil)).Cmp(want) != 0 { t.Errorf("Inverse property not satisfied: got %s; want %s", z.Format('g', 10), test.z) } }