Esempio n. 1
0
func (z *Big) needsInc(x, r int64, pos, odd bool) bool {
	m := 1
	if r > math.MinInt64/2 || r <= math.MaxInt64/2 {
		m = arith.AbsCmp(r<<1, x)
	}
	return z.ctx.mode.needsInc(m, pos, odd)
}
Esempio n. 2
0
// cmpNorm compares x and y in the range [0.1, 0.999...] and
// returns true if x > y.
func cmpNorm(x int64, xs int32, y int64, ys int32) (ok bool) {
	if debug && (x == 0 || y == 0) {
		panic("x and/or y cannot be zero")
	}
	if diff := xs - ys; diff != 0 {
		if diff < 0 {
			x, ok = checked.MulPow10(x, -diff)
		} else {
			y, ok = checked.MulPow10(y, diff)
		}
	}
	if x != c.Inflated {
		if y != c.Inflated {
			return arith.AbsCmp(x, y) > 0
		}
		return false
	}
	return true
}
Esempio n. 3
0
// Cmp compares d and x and returns:
//
//   -1 if z <  x
//    0 if z == x
//   +1 if z >  x
//
// It does not modify d or x.
func (z *Big) Cmp(x *Big) int {
	// Check for same pointers.
	if z == x {
		return 0
	}

	// Same scales means we can compare straight across.
	if z.scale == x.scale {
		if z.isCompact() && x.isCompact() {
			if z.compact > x.compact {
				return +1
			}
			if z.compact < x.compact {
				return -1
			}
			return 0
		}
		if z.isInflated() && x.isInflated() {
			if z.mantissa.Sign() != x.mantissa.Sign() {
				return z.mantissa.Sign()
			}

			if z.scale < 0 {
				return z.mantissa.Cmp(&x.mantissa)
			}

			zb := z.mantissa.Bits()
			xb := x.mantissa.Bits()

			min := len(zb)
			if len(xb) < len(zb) {
				min = len(xb)
			}
			i := 0
			for i < min-1 && zb[i] == xb[i] {
				i++
			}
			if zb[i] > xb[i] {
				return +1
			}
			if zb[i] < xb[i] {
				return -1
			}
			return 0
		}
	}

	// Different scales -- check signs and/or if they're
	// both zero.

	ds := z.Sign()
	xs := x.Sign()
	switch {
	case ds > xs:
		return +1
	case ds < xs:
		return -1
	case ds == 0 && xs == 0:
		return 0
	}

	// Scales aren't equal, the signs are the same, and both
	// are non-zero.
	dl := int32(z.Prec()) - z.scale
	xl := int32(x.Prec()) - x.scale
	if dl > xl {
		return +1
	}
	if dl < xl {
		return -1
	}

	// We need to inflate one of the numbers.

	dc := z.compact // hi
	xc := x.compact // lo

	var swap bool

	hi, lo := z, x
	if hi.scale < lo.scale {
		hi, lo = lo, hi
		dc, xc = xc, dc
		swap = true // d is lo
	}

	diff := hi.scale - lo.scale
	if diff <= c.BadScale {
		var ok bool
		xc, ok = checked.MulPow10(xc, diff)
		if !ok && dc == c.Inflated {
			// d is lo
			if swap {
				zm := new(big.Int).Set(&z.mantissa)
				return checked.MulBigPow10(zm, diff).Cmp(&x.mantissa)
			}
			// x is lo
			xm := new(big.Int).Set(&x.mantissa)
			return z.mantissa.Cmp(checked.MulBigPow10(xm, diff))
		}
	}

	if swap {
		dc, xc = xc, dc
	}

	if dc != c.Inflated {
		if xc != c.Inflated {
			return arith.AbsCmp(dc, xc)
		}
		return big.NewInt(dc).Cmp(&x.mantissa)
	}
	if xc != c.Inflated {
		return z.mantissa.Cmp(big.NewInt(xc))
	}
	return z.mantissa.Cmp(&x.mantissa)
}