Commit 85c32c37 authored by griesemer's avatar griesemer Committed by Robert Griesemer

math/big: implement CmpAbs

Fixes #22473.

Change-Id: Ie886dfc8b5510970d6d63ca6472c73325f6f2276
Reviewed-on: https://go-review.googlesource.com/74971
Run-TryBot: Robert Griesemer <gri@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: 's avatarMartin Möhrmann <moehrmann@google.com>
parent 18525735
......@@ -329,6 +329,16 @@ func (x *Int) Cmp(y *Int) (r int) {
return
}
// CmpAbs compares the absolute values of x and y and returns:
//
// -1 if |x| < |y|
// 0 if |x| == |y|
// +1 if |x| > |y|
//
func (x *Int) CmpAbs(y *Int) int {
return x.abs.cmp(y.abs)
}
// low32 returns the least significant 32 bits of x.
func low32(x nat) uint32 {
if len(x) == 0 {
......
......@@ -929,6 +929,63 @@ func TestLshRsh(t *testing.T) {
}
}
// Entries must be sorted by value in ascending order.
var cmpAbsTests = []string{
"0",
"1",
"2",
"10",
"10000000",
"2783678367462374683678456387645876387564783686583485",
"2783678367462374683678456387645876387564783686583486",
"32957394867987420967976567076075976570670947609750670956097509670576075067076027578341538",
}
func TestCmpAbs(t *testing.T) {
values := make([]*Int, len(cmpAbsTests))
var prev *Int
for i, s := range cmpAbsTests {
x, ok := new(Int).SetString(s, 0)
if !ok {
t.Fatalf("SetString(%s, 0) failed", s)
}
if prev != nil && prev.Cmp(x) >= 0 {
t.Fatal("cmpAbsTests entries not sorted in ascending order")
}
values[i] = x
prev = x
}
for i, x := range values {
for j, y := range values {
// try all combinations of signs for x, y
for k := 0; k < 4; k++ {
var a, b Int
a.Set(x)
b.Set(y)
if k&1 != 0 {
a.Neg(&a)
}
if k&2 != 0 {
b.Neg(&b)
}
got := a.CmpAbs(&b)
want := 0
switch {
case i > j:
want = 1
case i < j:
want = -1
}
if got != want {
t.Errorf("absCmp |%s|, |%s|: got %d; want %d", &a, &b, got, want)
}
}
}
}
}
var int64Tests = []string{
// int64
"0",
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment