Exemplo n.º 1
0
func TestDecimal_Hypot(t *testing.T) {
	tests := [...]struct {
		p, q *decimal.Big
		c    int32
		a    string
	}{
		{decimal.New(1, 0), decimal.New(4, 0), 15, "4.12310562561766"},
		{decimal.New(1, 0), decimal.New(4, 0), 10, "4.1231056256"},
		{Pi, Pi, 75, "4.442882938158366247015880990060693698614621689375690223085395606956434793099"},
		{decimal.New(-12, 0), decimal.New(599, 0), 2, "599.12"},
		{decimal.New(1234, 3), decimal.New(987654123, 5), 2, "9876.54"},
		{decimal.New(3, 0), decimal.New(4, 0), 0, "5"},
	}
	var a decimal.Big
	for i, v := range tests {
		a.SetPrec(v.c)
		if got := Hypot(&a, v.p, v.q).String(); got != v.a {
			t.Errorf("#%d: wanted %q, got %q", i, v.a, got)
		}
	}
}
Exemplo n.º 2
0
// Hypot sets z to Sqrt(p*p + q*q) and returns z.
func Hypot(z, p, q *decimal.Big) *decimal.Big {
	p0 := new(decimal.Big).Set(p)
	q0 := new(decimal.Big).Set(q)
	if p0.Sign() <= 0 {
		p0.Neg(p0)
	}
	if q0.Sign() <= 0 {
		q0.Neg(q0)
	}
	if p0.Sign() == 0 {
		return z.SetMantScale(0, 0)
	}
	p0.Mul(p0, p0)
	q0.Mul(q0, q0)
	return Sqrt(z, p0.Add(p0, q0))
}
Exemplo n.º 3
0
// Sqrt sets z to the square root of x and returns z.
// The precision of Sqrt is determined by z's Context.
// Sqrt will panic on negative values since decimal.Big cannot
// represent imaginary numbers.
func Sqrt(z, x *decimal.Big) *decimal.Big {
	return z.Sqrt(x)
}