mirror of
https://github.com/golang/go
synced 2024-11-13 18:10:24 -07:00
math/big: permit passing of (possibly nil) *Float to MantExp to avoid allocation
Change-Id: Ia92eea833283f8b16fa09d4ca1c9cb3bc0eb18a2 Reviewed-on: https://go-review.googlesource.com/5870 Reviewed-by: Rob Pike <r@golang.org>
This commit is contained in:
parent
9b3ccc082f
commit
18fd940620
@ -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
|
||||
}
|
||||
|
@ -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)
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user