Commit e5a0d639 authored by Robert Griesemer's avatar Robert Griesemer

cmd/internal/gc/big: vendored math/big for use by gc

This is vendored copy of the pure-Go version of math/big.
To update, run vendor.bash in place.

This will permit the use of the new big.Float functionality in
gc (which is not available in 1.4, the version used for bootstrapping).

Change-Id: I4dcdea875d54710005ca3fdea2e0e30422b1b46d
Reviewed-on: https://go-review.googlesource.com/7857Reviewed-by: default avatarBrad Fitzpatrick <bradfitz@golang.org>
Run-TryBot: Robert Griesemer <gri@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: default avatarRuss Cox <rsc@golang.org>
parent a1bb3030
// generated by stringer -type=Accuracy; DO NOT EDIT
package big
import "fmt"
const _Accuracy_name = "ExactBelowAboveUndef"
var _Accuracy_index = [...]uint8{0, 5, 10, 15, 20}
func (i Accuracy) String() string {
if i < 0 || i+1 >= Accuracy(len(_Accuracy_index)) {
return fmt.Sprintf("Accuracy(%d)", i)
}
return _Accuracy_name[_Accuracy_index[i]:_Accuracy_index[i+1]]
}
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This file provides Go implementations of elementary multi-precision
// arithmetic operations on word vectors. Needed for platforms without
// assembly implementations of these routines.
package big
// A Word represents a single digit of a multi-precision unsigned integer.
type Word uintptr
const (
// Compute the size _S of a Word in bytes.
_m = ^Word(0)
_logS = _m>>8&1 + _m>>16&1 + _m>>32&1
_S = 1 << _logS
_W = _S << 3 // word size in bits
_B = 1 << _W // digit base
_M = _B - 1 // digit mask
_W2 = _W / 2 // half word size in bits
_B2 = 1 << _W2 // half digit base
_M2 = _B2 - 1 // half digit mask
)
// ----------------------------------------------------------------------------
// Elementary operations on words
//
// These operations are used by the vector operations below.
// z1<<_W + z0 = x+y+c, with c == 0 or 1
func addWW_g(x, y, c Word) (z1, z0 Word) {
yc := y + c
z0 = x + yc
if z0 < x || yc < y {
z1 = 1
}
return
}
// z1<<_W + z0 = x-y-c, with c == 0 or 1
func subWW_g(x, y, c Word) (z1, z0 Word) {
yc := y + c
z0 = x - yc
if z0 > x || yc < y {
z1 = 1
}
return
}
// z1<<_W + z0 = x*y
// Adapted from Warren, Hacker's Delight, p. 132.
func mulWW_g(x, y Word) (z1, z0 Word) {
x0 := x & _M2
x1 := x >> _W2
y0 := y & _M2
y1 := y >> _W2
w0 := x0 * y0
t := x1*y0 + w0>>_W2
w1 := t & _M2
w2 := t >> _W2
w1 += x0 * y1
z1 = x1*y1 + w2 + w1>>_W2
z0 = x * y
return
}
// z1<<_W + z0 = x*y + c
func mulAddWWW_g(x, y, c Word) (z1, z0 Word) {
z1, zz0 := mulWW_g(x, y)
if z0 = zz0 + c; z0 < zz0 {
z1++
}
return
}
// Length of x in bits.
func bitLen_g(x Word) (n int) {
for ; x >= 0x8000; x >>= 16 {
n += 16
}
if x >= 0x80 {
x >>= 8
n += 8
}
if x >= 0x8 {
x >>= 4
n += 4
}
if x >= 0x2 {
x >>= 2
n += 2
}
if x >= 0x1 {
n++
}
return
}
// log2 computes the integer binary logarithm of x.
// The result is the integer n for which 2^n <= x < 2^(n+1).
// If x == 0, the result is -1.
func log2(x Word) int {
return bitLen(x) - 1
}
// Number of leading zeros in x.
func leadingZeros(x Word) uint {
return uint(_W - bitLen(x))
}
// q = (u1<<_W + u0 - r)/y
// Adapted from Warren, Hacker's Delight, p. 152.
func divWW_g(u1, u0, v Word) (q, r Word) {
if u1 >= v {
return 1<<_W - 1, 1<<_W - 1
}
s := leadingZeros(v)
v <<= s
vn1 := v >> _W2
vn0 := v & _M2
un32 := u1<<s | u0>>(_W-s)
un10 := u0 << s
un1 := un10 >> _W2
un0 := un10 & _M2
q1 := un32 / vn1
rhat := un32 - q1*vn1
for q1 >= _B2 || q1*vn0 > _B2*rhat+un1 {
q1--
rhat += vn1
if rhat >= _B2 {
break
}
}
un21 := un32*_B2 + un1 - q1*v
q0 := un21 / vn1
rhat = un21 - q0*vn1
for q0 >= _B2 || q0*vn0 > _B2*rhat+un0 {
q0--
rhat += vn1
if rhat >= _B2 {
break
}
}
return q1*_B2 + q0, (un21*_B2 + un0 - q0*v) >> s
}
// Keep for performance debugging.
// Using addWW_g is likely slower.
const use_addWW_g = false
// The resulting carry c is either 0 or 1.
func addVV_g(z, x, y []Word) (c Word) {
if use_addWW_g {
for i := range z {
c, z[i] = addWW_g(x[i], y[i], c)
}
return
}
for i, xi := range x[:len(z)] {
yi := y[i]
zi := xi + yi + c
z[i] = zi
// see "Hacker's Delight", section 2-12 (overflow detection)
c = (xi&yi | (xi|yi)&^zi) >> (_W - 1)
}
return
}
// The resulting carry c is either 0 or 1.
func subVV_g(z, x, y []Word) (c Word) {
if use_addWW_g {
for i := range z {
c, z[i] = subWW_g(x[i], y[i], c)
}
return
}
for i, xi := range x[:len(z)] {
yi := y[i]
zi := xi - yi - c
z[i] = zi
// see "Hacker's Delight", section 2-12 (overflow detection)
c = (yi&^xi | (yi|^xi)&zi) >> (_W - 1)
}
return
}
// Argument y must be either 0 or 1.
// The resulting carry c is either 0 or 1.
func addVW_g(z, x []Word, y Word) (c Word) {
if use_addWW_g {
c = y
for i := range z {
c, z[i] = addWW_g(x[i], c, 0)
}
return
}
c = y
for i, xi := range x[:len(z)] {
zi := xi + c
z[i] = zi
c = xi &^ zi >> (_W - 1)
}
return
}
func subVW_g(z, x []Word, y Word) (c Word) {
if use_addWW_g {
c = y
for i := range z {
c, z[i] = subWW_g(x[i], c, 0)
}
return
}
c = y
for i, xi := range x[:len(z)] {
zi := xi - c
z[i] = zi
c = (zi &^ xi) >> (_W - 1)
}
return
}
func shlVU_g(z, x []Word, s uint) (c Word) {
if n := len(z); n > 0 {
ŝ := _W - s
w1 := x[n-1]
c = w1 >> ŝ
for i := n - 1; i > 0; i-- {
w := w1
w1 = x[i-1]
z[i] = w<<s | w1>>ŝ
}
z[0] = w1 << s
}
return
}
func shrVU_g(z, x []Word, s uint) (c Word) {
if n := len(z); n > 0 {
ŝ := _W - s
w1 := x[0]
c = w1 << ŝ
for i := 0; i < n-1; i++ {
w := w1
w1 = x[i+1]
z[i] = w>>s | w1<<ŝ
}
z[n-1] = w1 >> s
}
return
}
func mulAddVWW_g(z, x []Word, y, r Word) (c Word) {
c = r
for i := range z {
c, z[i] = mulAddWWW_g(x[i], y, c)
}
return
}
// TODO(gri) Remove use of addWW_g here and then we can remove addWW_g and subWW_g.
func addMulVVW_g(z, x []Word, y Word) (c Word) {
for i := range z {
z1, z0 := mulAddWWW_g(x[i], y, z[i])
c, z[i] = addWW_g(z0, c, 0)
c += z1
}
return
}
func divWVW_g(z []Word, xn Word, x []Word, y Word) (r Word) {
r = xn
for i := len(z) - 1; i >= 0; i-- {
z[i], r = divWW_g(r, x[i], y)
}
return
}
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package big
func mulWW(x, y Word) (z1, z0 Word) {
return mulWW_g(x, y)
}
func divWW(x1, x0, y Word) (q, r Word) {
return divWW_g(x1, x0, y)
}
func addVV(z, x, y []Word) (c Word) {
return addVV_g(z, x, y)
}
func subVV(z, x, y []Word) (c Word) {
return subVV_g(z, x, y)
}
func addVW(z, x []Word, y Word) (c Word) {
return addVW_g(z, x, y)
}
func subVW(z, x []Word, y Word) (c Word) {
return subVW_g(z, x, y)
}
func shlVU(z, x []Word, s uint) (c Word) {
return shlVU_g(z, x, s)
}
func shrVU(z, x []Word, s uint) (c Word) {
return shrVU_g(z, x, s)
}
func mulAddVWW(z, x []Word, y, r Word) (c Word) {
return mulAddVWW_g(z, x, y, r)
}
func addMulVVW(z, x []Word, y Word) (c Word) {
return addMulVVW_g(z, x, y)
}
func divWVW(z []Word, xn Word, x []Word, y Word) (r Word) {
return divWVW_g(z, xn, x, y)
}
func bitLen(x Word) (n int) {
return bitLen_g(x)
}
This diff is collapsed.
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This file implements the Bits type used for testing Float operations
// via an independent (albeit slower) representations for floating-point
// numbers.
package big
import (
"fmt"
"sort"
"testing"
)
// A Bits value b represents a finite floating-point number x of the form
//
// x = 2**b[0] + 2**b[1] + ... 2**b[len(b)-1]
//
// The order of slice elements is not significant. Negative elements may be
// used to form fractions. A Bits value is normalized if each b[i] occurs at
// most once. For instance Bits{0, 0, 1} is not normalized but represents the
// same floating-point number as Bits{2}, which is normalized. The zero (nil)
// value of Bits is a ready to use Bits value and represents the value 0.
type Bits []int
func (x Bits) add(y Bits) Bits {
return append(x, y...)
}
func (x Bits) mul(y Bits) Bits {
var p Bits
for _, x := range x {
for _, y := range y {
p = append(p, x+y)
}
}
return p
}
func TestMulBits(t *testing.T) {
for _, test := range []struct {
x, y, want Bits
}{
{nil, nil, nil},
{Bits{}, Bits{}, nil},
{Bits{0}, Bits{0}, Bits{0}},
{Bits{0}, Bits{1}, Bits{1}},
{Bits{1}, Bits{1, 2, 3}, Bits{2, 3, 4}},
{Bits{-1}, Bits{1}, Bits{0}},
{Bits{-10, -1, 0, 1, 10}, Bits{1, 2, 3}, Bits{-9, -8, -7, 0, 1, 2, 1, 2, 3, 2, 3, 4, 11, 12, 13}},
} {
got := fmt.Sprintf("%v", test.x.mul(test.y))
want := fmt.Sprintf("%v", test.want)
if got != want {
t.Errorf("%v * %v = %s; want %s", test.x, test.y, got, want)
}
}
}
// norm returns the normalized bits for x: It removes multiple equal entries
// by treating them as an addition (e.g., Bits{5, 5} => Bits{6}), and it sorts
// the result list for reproducible results.
func (x Bits) norm() Bits {
m := make(map[int]bool)
for _, b := range x {
for m[b] {
m[b] = false
b++
}
m[b] = true
}
var z Bits
for b, set := range m {
if set {
z = append(z, b)
}
}
sort.Ints([]int(z))
return z
}
func TestNormBits(t *testing.T) {
for _, test := range []struct {
x, want Bits
}{
{nil, nil},
{Bits{}, Bits{}},
{Bits{0}, Bits{0}},
{Bits{0, 0}, Bits{1}},
{Bits{3, 1, 1}, Bits{2, 3}},
{Bits{10, 9, 8, 7, 6, 6}, Bits{11}},
} {
got := fmt.Sprintf("%v", test.x.norm())
want := fmt.Sprintf("%v", test.want)
if got != want {
t.Errorf("normBits(%v) = %s; want %s", test.x, got, want)
}
}
}
// round returns the Float value corresponding to x after rounding x
// to prec bits according to mode.
func (x Bits) round(prec uint, mode RoundingMode) *Float {
x = x.norm()
// determine range
var min, max int
for i, b := range x {
if i == 0 || b < min {
min = b
}
if i == 0 || b > max {
max = b
}
}
prec0 := uint(max + 1 - min)
if prec >= prec0 {
return x.Float()
}
// prec < prec0
// determine bit 0, rounding, and sticky bit, and result bits z
var bit0, rbit, sbit uint
var z Bits
r := max - int(prec)
for _, b := range x {
switch {
case b == r:
rbit = 1
case b < r:
sbit = 1
default:
// b > r
if b == r+1 {
bit0 = 1
}
z = append(z, b)
}
}
// round
f := z.Float() // rounded to zero
if mode == ToNearestAway {
panic("not yet implemented")
}
if mode == ToNearestEven && rbit == 1 && (sbit == 1 || sbit == 0 && bit0 != 0) || mode == AwayFromZero {
// round away from zero
f.SetMode(ToZero).SetPrec(prec)
f.Add(f, Bits{int(r) + 1}.Float())
}
return f
}
// Float returns the *Float z of the smallest possible precision such that
// z = sum(2**bits[i]), with i = range bits. If multiple bits[i] are equal,
// they are added: Bits{0, 1, 0}.Float() == 2**0 + 2**1 + 2**0 = 4.
func (bits Bits) Float() *Float {
// handle 0
if len(bits) == 0 {
return new(Float)
}
// len(bits) > 0
// determine lsb exponent
var min int
for i, b := range bits {
if i == 0 || b < min {
min = b
}
}
// create bit pattern
x := NewInt(0)
for _, b := range bits {
badj := b - min
// propagate carry if necessary
for x.Bit(badj) != 0 {
x.SetBit(x, badj, 0)
badj++
}
x.SetBit(x, badj, 1)
}
// create corresponding float
z := new(Float).SetInt(x) // normalized
if e := int64(z.exp) + int64(min); MinExp <= e && e <= MaxExp {
z.exp = int32(e)
} else {
// this should never happen for our test cases
panic("exponent out of range")
}
return z
}
func TestFromBits(t *testing.T) {
for _, test := range []struct {
bits Bits
want string
}{
// all different bit numbers
{nil, "0"},
{Bits{0}, "0x.8p1"},
{Bits{1}, "0x.8p2"},
{Bits{-1}, "0x.8p0"},
{Bits{63}, "0x.8p64"},
{Bits{33, -30}, "0x.8000000000000001p34"},
{Bits{255, 0}, "0x.8000000000000000000000000000000000000000000000000000000000000001p256"},
// multiple equal bit numbers
{Bits{0, 0}, "0x.8p2"},
{Bits{0, 0, 0, 0}, "0x.8p3"},
{Bits{0, 1, 0}, "0x.8p3"},
{append(Bits{2, 1, 0} /* 7 */, Bits{3, 1} /* 10 */ ...), "0x.88p5" /* 17 */},
} {
f := test.bits.Float()
if got := f.Format('p', 0); got != test.want {
t.Errorf("setBits(%v) = %s; want %s", test.bits, got, test.want)
}
}
}
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This file prints execution times for the Mul benchmark
// given different Karatsuba thresholds. The result may be
// used to manually fine-tune the threshold constant. The
// results are somewhat fragile; use repeated runs to get
// a clear picture.
// Usage: go test -run=TestCalibrate -calibrate
package big
import (
"flag"
"fmt"
"testing"
"time"
)
var calibrate = flag.Bool("calibrate", false, "run calibration test")
func karatsubaLoad(b *testing.B) {
BenchmarkMul(b)
}
// measureKaratsuba returns the time to run a Karatsuba-relevant benchmark
// given Karatsuba threshold th.
func measureKaratsuba(th int) time.Duration {
th, karatsubaThreshold = karatsubaThreshold, th
res := testing.Benchmark(karatsubaLoad)
karatsubaThreshold = th
return time.Duration(res.NsPerOp())
}
func computeThresholds() {
fmt.Printf("Multiplication times for varying Karatsuba thresholds\n")
fmt.Printf("(run repeatedly for good results)\n")
// determine Tk, the work load execution time using basic multiplication
Tb := measureKaratsuba(1e9) // th == 1e9 => Karatsuba multiplication disabled
fmt.Printf("Tb = %10s\n", Tb)
// thresholds
th := 4
th1 := -1
th2 := -1
var deltaOld time.Duration
for count := -1; count != 0 && th < 128; count-- {
// determine Tk, the work load execution time using Karatsuba multiplication
Tk := measureKaratsuba(th)
// improvement over Tb
delta := (Tb - Tk) * 100 / Tb
fmt.Printf("th = %3d Tk = %10s %4d%%", th, Tk, delta)
// determine break-even point
if Tk < Tb && th1 < 0 {
th1 = th
fmt.Print(" break-even point")
}
// determine diminishing return
if 0 < delta && delta < deltaOld && th2 < 0 {
th2 = th
fmt.Print(" diminishing return")
}
deltaOld = delta
fmt.Println()
// trigger counter
if th1 >= 0 && th2 >= 0 && count < 0 {
count = 10 // this many extra measurements after we got both thresholds
}
th++
}
}
func TestCalibrate(t *testing.T) {
if *calibrate {
computeThresholds()
}
}
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This file implements multi-precision decimal numbers.
// The implementation is for float to decimal conversion only;
// not general purpose use.
// The only operations are precise conversion from binary to
// decimal and rounding.
//
// The key observation and some code (shr) is borrowed from
// strconv/decimal.go: conversion of binary fractional values can be done
// precisely in multi-precision decimal because 2 divides 10 (required for
// >> of mantissa); but conversion of decimal floating-point values cannot
// be done precisely in binary representation.
//
// In contrast to strconv/decimal.go, only right shift is implemented in
// decimal format - left shift can be done precisely in binary format.
package big
// A decimal represents a floating-point number in decimal representation.
// The value of a decimal x is x.mant * 10 ** x.exp with 0.5 <= x.mant < 1,
// with the most-significant mantissa digit at index 0.
type decimal struct {
mant []byte // mantissa ASCII digits, big-endian
exp int // exponent, valid if len(mant) > 0
}
// Maximum shift amount that can be done in one pass without overflow.
// A Word has _W bits and (1<<maxShift - 1)*10 + 9 must fit into Word.
const maxShift = _W - 4
// TODO(gri) Since we know the desired decimal precision when converting
// a floating-point number, we may be able to limit the number of decimal
// digits that need to be computed by init by providing an additional
// precision argument and keeping track of when a number was truncated early
// (equivalent of "sticky bit" in binary rounding).
// TODO(gri) Along the same lines, enforce some limit to shift magnitudes
// to avoid "infinitely" long running conversions (until we run out of space).
// Init initializes x to the decimal representation of m << shift (for
// shift >= 0), or m >> -shift (for shift < 0).
func (x *decimal) init(m nat, shift int) {
// special case 0
if len(m) == 0 {
x.mant = x.mant[:0]
return
}
// Optimization: If we need to shift right, first remove any trailing
// zero bits from m to reduce shift amount that needs to be done in
// decimal format (since that is likely slower).
if shift < 0 {
ntz := m.trailingZeroBits()
s := uint(-shift)
if s >= ntz {
s = ntz // shift at most ntz bits
}
m = nat(nil).shr(m, s)
shift += int(s)
}
// Do any shift left in binary representation.
if shift > 0 {
m = nat(nil).shl(m, uint(shift))
shift = 0
}
// Convert mantissa into decimal representation.
s := m.decimalString() // TODO(gri) avoid string conversion here
n := len(s)
x.exp = n
// Trim trailing zeros; instead the exponent is tracking
// the decimal point independent of the number of digits.
for n > 0 && s[n-1] == '0' {
n--
}
x.mant = append(x.mant[:0], s[:n]...)
// Do any (remaining) shift right in decimal representation.
if shift < 0 {
for shift < -maxShift {
shr(x, maxShift)
shift += maxShift
}
shr(x, uint(-shift))
}
}
// Possibly optimization: The current implementation of nat.string takes
// a charset argument. When a right shift is needed, we could provide
// "\x00\x01...\x09" instead of "012..9" (as in nat.decimalString) and
// avoid the repeated +'0' and -'0' operations in decimal.shr (and do a
// single +'0' pass at the end).
// shr implements x >> s, for s <= maxShift.
func shr(x *decimal, s uint) {
// Division by 1<<s using shift-and-subtract algorithm.
// pick up enough leading digits to cover first shift
r := 0 // read index
var n Word
for n>>s == 0 && r < len(x.mant) {
ch := Word(x.mant[r])
r++
n = n*10 + ch - '0'
}
if n == 0 {
// x == 0; shouldn't get here, but handle anyway
x.mant = x.mant[:0]
return
}
for n>>s == 0 {
r++
n *= 10
}
x.exp += 1 - r
// read a digit, write a digit
w := 0 // write index
for r < len(x.mant) {
ch := Word(x.mant[r])
r++
d := n >> s
n -= d << s
x.mant[w] = byte(d + '0')
w++
n = n*10 + ch - '0'
}
// write extra digits that still fit
for n > 0 && w < len(x.mant) {
d := n >> s
n -= d << s
x.mant[w] = byte(d + '0')
w++
n = n * 10
}
x.mant = x.mant[:w] // the number may be shorter (e.g. 1024 >> 10)
// append additional digits that didn't fit
for n > 0 {
d := n >> s
n -= d << s
x.mant = append(x.mant, byte(d+'0'))
n = n * 10
}
trim(x)
}
func (x *decimal) String() string {
if len(x.mant) == 0 {
return "0"
}
var buf []byte
switch {
case x.exp <= 0:
// 0.00ddd
buf = append(buf, "0."...)
buf = appendZeros(buf, -x.exp)
buf = append(buf, x.mant...)
case /* 0 < */ x.exp < len(x.mant):
// dd.ddd
buf = append(buf, x.mant[:x.exp]...)
buf = append(buf, '.')
buf = append(buf, x.mant[x.exp:]...)
default: // len(x.mant) <= x.exp
// ddd00
buf = append(buf, x.mant...)
buf = appendZeros(buf, x.exp-len(x.mant))
}
return string(buf)
}
// appendZeros appends n 0 digits to buf and returns buf.
func appendZeros(buf []byte, n int) []byte {
for ; n > 0; n-- {
buf = append(buf, '0')
}
return buf
}
// shouldRoundUp reports if x should be rounded up
// if shortened to n digits. n must be a valid index
// for x.mant.
func shouldRoundUp(x *decimal, n int) bool {
if x.mant[n] == '5' && n+1 == len(x.mant) {
// exactly halfway - round to even
return n > 0 && (x.mant[n-1]-'0')&1 != 0
}
// not halfway - digit tells all (x.mant has no trailing zeros)
return x.mant[n] >= '5'
}
// round sets x to (at most) n mantissa digits by rounding it
// to the nearest even value with n (or fever) mantissa digits.
// If n < 0, x remains unchanged.
func (x *decimal) round(n int) {
if n < 0 || n >= len(x.mant) {
return // nothing to do
}
if shouldRoundUp(x, n) {
x.roundUp(n)
} else {
x.roundDown(n)
}
}
func (x *decimal) roundUp(n int) {
if n < 0 || n >= len(x.mant) {
return // nothing to do
}
// 0 <= n < len(x.mant)
// find first digit < '9'
for n > 0 && x.mant[n-1] >= '9' {
n--
}
if n == 0 {
// all digits are '9's => round up to '1' and update exponent
x.mant[0] = '1' // ok since len(x.mant) > n
x.mant = x.mant[:1]
x.exp++
return
}
// n > 0 && x.mant[n-1] < '9'
x.mant[n-1]++
x.mant = x.mant[:n]
// x already trimmed
}
func (x *decimal) roundDown(n int) {
if n < 0 || n >= len(x.mant) {
return // nothing to do
}
x.mant = x.mant[:n]
trim(x)
}
// trim cuts off any trailing zeros from x's mantissa;
// they are meaningless for the value of x.
func trim(x *decimal) {
i := len(x.mant)
for i > 0 && x.mant[i-1] == '0' {
i--
}
x.mant = x.mant[:i]
}
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package big
import "testing"
func TestDecimalString(t *testing.T) {
for _, test := range []struct {
x decimal
want string
}{
{want: "0"},
{decimal{nil, 1000}, "0"}, // exponent of 0 is ignored
{decimal{[]byte("12345"), 0}, "0.12345"},
{decimal{[]byte("12345"), -3}, "0.00012345"},
{decimal{[]byte("12345"), +3}, "123.45"},
{decimal{[]byte("12345"), +10}, "1234500000"},
} {
if got := test.x.String(); got != test.want {
t.Errorf("%v == %s; want %s", test.x, got, test.want)
}
}
}
func TestDecimalInit(t *testing.T) {
for _, test := range []struct {
x Word
shift int
want string
}{
{0, 0, "0"},
{0, -100, "0"},
{0, 100, "0"},
{1, 0, "1"},
{1, 10, "1024"},
{1, 100, "1267650600228229401496703205376"},
{1, -100, "0.0000000000000000000000000000007888609052210118054117285652827862296732064351090230047702789306640625"},
{12345678, 8, "3160493568"},
{12345678, -8, "48225.3046875"},
{195312, 9, "99999744"},
{1953125, 9, "1000000000"},
} {
var d decimal
d.init(nat{test.x}.norm(), test.shift)
if got := d.String(); got != test.want {
t.Errorf("%d << %d == %s; want %s", test.x, test.shift, got, test.want)
}
}
}
func TestDecimalRounding(t *testing.T) {
for _, test := range []struct {
x uint64
n int
down, even, up string
}{
{0, 0, "0", "0", "0"},
{0, 1, "0", "0", "0"},
{1, 0, "0", "0", "10"},
{5, 0, "0", "0", "10"},
{9, 0, "0", "10", "10"},
{15, 1, "10", "20", "20"},
{45, 1, "40", "40", "50"},
{95, 1, "90", "100", "100"},
{12344999, 4, "12340000", "12340000", "12350000"},
{12345000, 4, "12340000", "12340000", "12350000"},
{12345001, 4, "12340000", "12350000", "12350000"},
{23454999, 4, "23450000", "23450000", "23460000"},
{23455000, 4, "23450000", "23460000", "23460000"},
{23455001, 4, "23450000", "23460000", "23460000"},
{99994999, 4, "99990000", "99990000", "100000000"},
{99995000, 4, "99990000", "100000000", "100000000"},
{99999999, 4, "99990000", "100000000", "100000000"},
{12994999, 4, "12990000", "12990000", "13000000"},
{12995000, 4, "12990000", "13000000", "13000000"},
{12999999, 4, "12990000", "13000000", "13000000"},
} {
x := nat(nil).setUint64(test.x)
var d decimal
d.init(x, 0)
d.roundDown(test.n)
if got := d.String(); got != test.down {
t.Errorf("roundDown(%d, %d) = %s; want %s", test.x, test.n, got, test.down)
}
d.init(x, 0)
d.round(test.n)
if got := d.String(); got != test.even {
t.Errorf("round(%d, %d) = %s; want %s", test.x, test.n, got, test.even)
}
d.init(x, 0)
d.roundUp(test.n)
if got := d.String(); got != test.up {
t.Errorf("roundUp(%d, %d) = %s; want %s", test.x, test.n, got, test.up)
}
}
}
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package big_test
import (
"fmt"
"log"
"math/big"
)
func ExampleRat_SetString() {
r := new(big.Rat)
r.SetString("355/113")
fmt.Println(r.FloatString(3))
// Output: 3.142
}
func ExampleInt_SetString() {
i := new(big.Int)
i.SetString("644", 8) // octal
fmt.Println(i)
// Output: 420
}
func ExampleRat_Scan() {
// The Scan function is rarely used directly;
// the fmt package recognizes it as an implementation of fmt.Scanner.
r := new(big.Rat)
_, err := fmt.Sscan("1.5000", r)
if err != nil {
log.Println("error scanning value:", err)
} else {
fmt.Println(r)
}
// Output: 3/2
}
func ExampleInt_Scan() {
// The Scan function is rarely used directly;
// the fmt package recognizes it as an implementation of fmt.Scanner.
i := new(big.Int)
_, err := fmt.Sscan("18446744073709551617", i)
if err != nil {
log.Println("error scanning value:", err)
} else {
fmt.Println(i)
}
// Output: 18446744073709551617
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This file implements a GCD benchmark.
// Usage: go test math/big -test.bench GCD
package big
import (
"math/rand"
"testing"
)
// randInt returns a pseudo-random Int in the range [1<<(size-1), (1<<size) - 1]
func randInt(r *rand.Rand, size uint) *Int {
n := new(Int).Lsh(intOne, size-1)
x := new(Int).Rand(r, n)
return x.Add(x, n) // make sure result > 1<<(size-1)
}
func runGCD(b *testing.B, aSize, bSize uint) {
b.StopTimer()
var r = rand.New(rand.NewSource(1234))
aa := randInt(r, aSize)
bb := randInt(r, bSize)
b.StartTimer()
for i := 0; i < b.N; i++ {
new(Int).GCD(nil, nil, aa, bb)
}
}
func BenchmarkGCD10x10(b *testing.B) { runGCD(b, 10, 10) }
func BenchmarkGCD10x100(b *testing.B) { runGCD(b, 10, 100) }
func BenchmarkGCD10x1000(b *testing.B) { runGCD(b, 10, 1000) }
func BenchmarkGCD10x10000(b *testing.B) { runGCD(b, 10, 10000) }
func BenchmarkGCD10x100000(b *testing.B) { runGCD(b, 10, 100000) }
func BenchmarkGCD100x100(b *testing.B) { runGCD(b, 100, 100) }
func BenchmarkGCD100x1000(b *testing.B) { runGCD(b, 100, 1000) }
func BenchmarkGCD100x10000(b *testing.B) { runGCD(b, 100, 10000) }
func BenchmarkGCD100x100000(b *testing.B) { runGCD(b, 100, 100000) }
func BenchmarkGCD1000x1000(b *testing.B) { runGCD(b, 1000, 1000) }
func BenchmarkGCD1000x10000(b *testing.B) { runGCD(b, 1000, 10000) }
func BenchmarkGCD1000x100000(b *testing.B) { runGCD(b, 1000, 100000) }
func BenchmarkGCD10000x10000(b *testing.B) { runGCD(b, 10000, 10000) }
func BenchmarkGCD10000x100000(b *testing.B) { runGCD(b, 10000, 100000) }
func BenchmarkGCD100000x100000(b *testing.B) { runGCD(b, 100000, 100000) }
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
// generated by stringer -type=RoundingMode; DO NOT EDIT
package big
import "fmt"
const _RoundingMode_name = "ToNearestEvenToNearestAwayToZeroAwayFromZeroToNegativeInfToPositiveInf"
var _RoundingMode_index = [...]uint8{0, 13, 26, 32, 44, 57, 70}
func (i RoundingMode) String() string {
if i+1 >= RoundingMode(len(_RoundingMode_index)) {
return fmt.Sprintf("RoundingMode(%d)", i)
}
return _RoundingMode_name[_RoundingMode_index[i]:_RoundingMode_index[i+1]]
}
This diff is collapsed.
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