...

Package big

import "math/big"
概览
索引
示例

概览 ▾

big 包实现了(大数的)高精度运算. 它支持以下数值类型:

- Int	带符号整数
- Rat	有理数

典型的方法形式如下:

func (z *Int) Op(x, y *Int) *Int	(*Rat 同理)

它实现了像 z = x Op y 这样的操作,并将其结果作为接收者;若接收者为操作数之一, 其值可能会被覆盖(而内存则会被重用)。为保留操作,其结果也会被返回。若该方法返回除 *Int 或 *Rat 之外的结果,其中一个操作数将被作为接收者。

索引 ▾

常量
func Jacobi(x, y *Int) int
type Accuracy
    func (i Accuracy) String() string
type ErrNaN
    func (err ErrNaN) Error() string
type Float
    func NewFloat(x float64) *Float
    func ParseFloat(s string, base int, prec uint, mode RoundingMode) (f *Float, b int, err error)
    func ScanFloat(r io.ByteScanner, base int, prec uint, mode RoundingMode) (f *Float, b int, err error)
    func (z *Float) Abs(x *Float) *Float
    func (x *Float) Acc() Accuracy
    func (z *Float) Add(x, y *Float) *Float
    func (x *Float) Append(buf []byte, format byte, prec int) []byte
    func (x *Float) Cmp(y *Float) int
    func (z *Float) Copy(x *Float) *Float
    func (x *Float) Float32() (float32, Accuracy)
    func (x *Float) Float64() (float64, Accuracy)
    func (x *Float) Format(format byte, prec int) string
    func (x *Float) Int(z *Int) (*Int, Accuracy)
    func (x *Float) Int64() (int64, Accuracy)
    func (x *Float) IsInf() bool
    func (x *Float) IsInt() bool
    func (x *Float) MantExp(mant *Float) (exp int)
    func (x *Float) MinPrec() uint
    func (x *Float) Mode() RoundingMode
    func (z *Float) Mul(x, y *Float) *Float
    func (z *Float) Neg(x *Float) *Float
    func (z *Float) Parse(s string, base int) (f *Float, b int, err error)
    func (x *Float) Prec() uint
    func (z *Float) Quo(x, y *Float) *Float
    func (x *Float) Rat(z *Rat) (*Rat, Accuracy)
    func (z *Float) Scan(r io.ByteScanner, base int) (f *Float, b int, err error)
    func (z *Float) Set(x *Float) *Float
    func (z *Float) SetFloat64(x float64) *Float
    func (z *Float) SetInf(signbit bool) *Float
    func (z *Float) SetInt(x *Int) *Float
    func (z *Float) SetInt64(x int64) *Float
    func (z *Float) SetMantExp(mant *Float, exp int) *Float
    func (z *Float) SetMode(mode RoundingMode) *Float
    func (z *Float) SetPrec(prec uint) *Float
    func (z *Float) SetRat(x *Rat) *Float
    func (z *Float) SetString(s string) (*Float, bool)
    func (z *Float) SetUint64(x uint64) *Float
    func (x *Float) Sign() int
    func (x *Float) Signbit() bool
    func (x *Float) String() string
    func (z *Float) Sub(x, y *Float) *Float
    func (x *Float) Uint64() (uint64, Accuracy)
type Int
    func NewInt(x int64) *Int
    func (z *Int) Abs(x *Int) *Int
    func (z *Int) Add(x, y *Int) *Int
    func (z *Int) And(x, y *Int) *Int
    func (z *Int) AndNot(x, y *Int) *Int
    func (z *Int) Binomial(n, k int64) *Int
    func (x *Int) Bit(i int) uint
    func (x *Int) BitLen() int
    func (x *Int) Bits() []Word
    func (x *Int) Bytes() []byte
    func (x *Int) Cmp(y *Int) (r int)
    func (z *Int) Div(x, y *Int) *Int
    func (z *Int) DivMod(x, y, m *Int) (*Int, *Int)
    func (z *Int) Exp(x, y, m *Int) *Int
    func (x *Int) Format(s fmt.State, ch rune)
    func (z *Int) GCD(x, y, a, b *Int) *Int
    func (z *Int) GobDecode(buf []byte) error
    func (x *Int) GobEncode() ([]byte, error)
    func (x *Int) Int64() int64
    func (z *Int) Lsh(x *Int, n uint) *Int
    func (z *Int) MarshalJSON() ([]byte, error)
    func (z *Int) MarshalText() (text []byte, err error)
    func (z *Int) Mod(x, y *Int) *Int
    func (z *Int) ModInverse(g, n *Int) *Int
    func (z *Int) ModSqrt(x, p *Int) *Int
    func (z *Int) Mul(x, y *Int) *Int
    func (z *Int) MulRange(a, b int64) *Int
    func (z *Int) Neg(x *Int) *Int
    func (z *Int) Not(x *Int) *Int
    func (z *Int) Or(x, y *Int) *Int
    func (x *Int) ProbablyPrime(n int) bool
    func (z *Int) Quo(x, y *Int) *Int
    func (z *Int) QuoRem(x, y, r *Int) (*Int, *Int)
    func (z *Int) Rand(rnd *rand.Rand, n *Int) *Int
    func (z *Int) Rem(x, y *Int) *Int
    func (z *Int) Rsh(x *Int, n uint) *Int
    func (z *Int) Scan(s fmt.ScanState, ch rune) error
    func (z *Int) Set(x *Int) *Int
    func (z *Int) SetBit(x *Int, i int, b uint) *Int
    func (z *Int) SetBits(abs []Word) *Int
    func (z *Int) SetBytes(buf []byte) *Int
    func (z *Int) SetInt64(x int64) *Int
    func (z *Int) SetString(s string, base int) (*Int, bool)
    func (z *Int) SetUint64(x uint64) *Int
    func (x *Int) Sign() int
    func (x *Int) String() string
    func (z *Int) Sub(x, y *Int) *Int
    func (x *Int) Uint64() uint64
    func (z *Int) UnmarshalJSON(text []byte) error
    func (z *Int) UnmarshalText(text []byte) error
    func (z *Int) Xor(x, y *Int) *Int
type Rat
    func NewRat(a, b int64) *Rat
    func (z *Rat) Abs(x *Rat) *Rat
    func (z *Rat) Add(x, y *Rat) *Rat
    func (x *Rat) Cmp(y *Rat) int
    func (x *Rat) Denom() *Int
    func (x *Rat) Float32() (f float32, exact bool)
    func (x *Rat) Float64() (f float64, exact bool)
    func (x *Rat) FloatString(prec int) string
    func (z *Rat) GobDecode(buf []byte) error
    func (x *Rat) GobEncode() ([]byte, error)
    func (z *Rat) Inv(x *Rat) *Rat
    func (x *Rat) IsInt() bool
    func (r *Rat) MarshalText() (text []byte, err error)
    func (z *Rat) Mul(x, y *Rat) *Rat
    func (z *Rat) Neg(x *Rat) *Rat
    func (x *Rat) Num() *Int
    func (z *Rat) Quo(x, y *Rat) *Rat
    func (x *Rat) RatString() string
    func (z *Rat) Scan(s fmt.ScanState, ch rune) error
    func (z *Rat) Set(x *Rat) *Rat
    func (z *Rat) SetFloat64(f float64) *Rat
    func (z *Rat) SetFrac(a, b *Int) *Rat
    func (z *Rat) SetFrac64(a, b int64) *Rat
    func (z *Rat) SetInt(x *Int) *Rat
    func (z *Rat) SetInt64(x int64) *Rat
    func (z *Rat) SetString(s string) (*Rat, bool)
    func (x *Rat) Sign() int
    func (x *Rat) String() string
    func (z *Rat) Sub(x, y *Rat) *Rat
    func (r *Rat) UnmarshalText(text []byte) error
type RoundingMode
    func (i RoundingMode) String() string
type Word
Bugs

包文件

accuracy_string.go arith.go arith_decl.go decimal.go float.go floatconv.go ftoa.go int.go intconv.go nat.go natconv.go rat.go ratconv.go roundingmode_string.go

常量

const (
    MaxExp  = math.MaxInt32  // largest supported exponent
    MinExp  = math.MinInt32  // smallest supported exponent
    MaxPrec = math.MaxUint32 // largest (theoretically) supported precision; likely memory-limited
)

Exponent and precision limits.

const MaxBase = 'z' - 'a' + 10 + 1

MaxBase is the largest number base accepted for string conversions.

func Jacobi

func Jacobi(x, y *Int) int

Jacobi returns the Jacobi symbol (x/y), either +1, -1, or 0. The y argument must be an odd integer.

type Accuracy

type Accuracy int8

Accuracy describes the rounding error produced by the most recent operation that generated a Float value, relative to the exact value.

const (
    Below Accuracy = -1
    Exact Accuracy = 0
    Above Accuracy = +1
)

Constants describing the Accuracy of a Float.

func (Accuracy) String

func (i Accuracy) String() string

type ErrNaN

type ErrNaN struct {
    // contains filtered or unexported fields
}

An ErrNaN panic is raised by a Float operation that would lead to a NaN under IEEE-754 rules. An ErrNaN implements the error interface.

func (ErrNaN) Error

func (err ErrNaN) Error() string

type Float

type Float struct {
    // contains filtered or unexported fields
}

A nonzero finite Float represents a multi-precision floating point number

sign × mantissa × 2**exponent

with 0.5 <= mantissa < 1.0, and MinExp <= exponent <= MaxExp. A Float may also be zero (+0, -0) or infinite (+Inf, -Inf). All Floats are ordered, and the ordering of two Floats x and y is defined by x.Cmp(y).

Each Float value also has a precision, rounding mode, and accuracy. The precision is the maximum number of mantissa bits available to represent the value. The rounding mode specifies how a result should be rounded to fit into the mantissa bits, and accuracy describes the rounding error with respect to the exact result.

Unless specified otherwise, all operations (including setters) that specify a *Float variable for the result (usually via the receiver with the exception of MantExp), round the numeric result according to the precision and rounding mode of the result variable.

If the provided result precision is 0 (see below), it is set to the precision of the argument with the largest precision value before any rounding takes place, and the rounding mode remains unchanged. Thus, uninitialized Floats provided as result arguments will have their precision set to a reasonable value determined by the operands and their mode is the zero value for RoundingMode (ToNearestEven).

By setting the desired precision to 24 or 53 and using matching rounding mode (typically ToNearestEven), Float operations produce the same results as the corresponding float32 or float64 IEEE-754 arithmetic for operands that correspond to normal (i.e., not denormal) float32 or float64 numbers. Exponent underflow and overflow lead to a 0 or an Infinity for different values than IEEE-754 because Float exponents have a much larger range.

The zero (uninitialized) value for a Float is ready to use and represents the number +0.0 exactly, with precision 0 and rounding mode ToNearestEven.

func NewFloat

func NewFloat(x float64) *Float

NewFloat allocates and returns a new Float set to x, with precision 53 and rounding mode ToNearestEven. NewFloat panics with ErrNaN if x is a NaN.

func ParseFloat

func ParseFloat(s string, base int, prec uint, mode RoundingMode) (f *Float, b int, err error)

ParseFloat is like f.Parse(s, base) with f set to the given precision and rounding mode.

func ScanFloat

func ScanFloat(r io.ByteScanner, base int, prec uint, mode RoundingMode) (f *Float, b int, err error)

ScanFloat is like f.Scan(r, base) with f set to the given precision and rounding mode.

func (*Float) Abs

func (z *Float) Abs(x *Float) *Float

Abs sets z to the (possibly rounded) value |x| (the absolute value of x) and returns z.

func (*Float) Acc

func (x *Float) Acc() Accuracy

Acc returns the accuracy of x produced by the most recent operation.

func (*Float) Add

func (z *Float) Add(x, y *Float) *Float

Add sets z to the rounded sum x+y and returns z. If z's precision is 0, it is changed to the larger of x's or y's precision before the operation. Rounding is performed according to z's precision and rounding mode; and z's accuracy reports the result error relative to the exact (not rounded) result. Add panics with ErrNaN if x and y are infinities with opposite signs. The value of z is undefined in that case.

BUG(gri) When rounding ToNegativeInf, the sign of Float values rounded to 0 is incorrect.

示例

代码:

// Operating on numbers of different precision.
var x, y, z big.Float
x.SetInt64(1000)          // x is automatically set to 64bit precision
y.SetFloat64(2.718281828) // y is automatically set to 53bit precision
z.SetPrec(32)
z.Add(&x, &y)
fmt.Printf("x = %s (%s, prec = %d, acc = %s)\n", &x, x.Format('p', 0), x.Prec(), x.Acc())
fmt.Printf("y = %s (%s, prec = %d, acc = %s)\n", &y, y.Format('p', 0), y.Prec(), y.Acc())
fmt.Printf("z = %s (%s, prec = %d, acc = %s)\n", &z, z.Format('p', 0), z.Prec(), z.Acc())

输出:

x = 1000 (0x.fap10, prec = 64, acc = Exact)
y = 2.718281828 (0x.adf85458248cd8p2, prec = 53, acc = Exact)
z = 1002.718282 (0x.faadf854p10, prec = 32, acc = Below)

func (*Float) Append

func (x *Float) Append(buf []byte, format byte, prec int) []byte

Append appends the string form of the floating-point number x, as generated by x.Format, to buf and returns the extended buffer.

func (*Float) Cmp

func (x *Float) Cmp(y *Float) int

Cmp compares x and y and returns:

-1 if x <  y
 0 if x == y (incl. -0 == 0, -Inf == -Inf, and +Inf == +Inf)
+1 if x >  y

示例

代码:

inf := math.Inf(1)
zero := 0.0

operands := []float64{-inf, -1.2, -zero, 0, +1.2, +inf}

fmt.Println("   x     y  cmp")
fmt.Println("---------------")
for _, x64 := range operands {
    x := big.NewFloat(x64)
    for _, y64 := range operands {
        y := big.NewFloat(y64)
        fmt.Printf("%4s  %4s  %3d\n", x, y, x.Cmp(y))
    }
    fmt.Println()
}

输出:

   x     y  cmp
---------------
-Inf  -Inf    0
-Inf  -1.2   -1
-Inf    -0   -1
-Inf     0   -1
-Inf   1.2   -1
-Inf  +Inf   -1

-1.2  -Inf    1
-1.2  -1.2    0
-1.2    -0   -1
-1.2     0   -1
-1.2   1.2   -1
-1.2  +Inf   -1

  -0  -Inf    1
  -0  -1.2    1
  -0    -0    0
  -0     0    0
  -0   1.2   -1
  -0  +Inf   -1

   0  -Inf    1
   0  -1.2    1
   0    -0    0
   0     0    0
   0   1.2   -1
   0  +Inf   -1

 1.2  -Inf    1
 1.2  -1.2    1
 1.2    -0    1
 1.2     0    1
 1.2   1.2    0
 1.2  +Inf   -1

+Inf  -Inf    1
+Inf  -1.2    1
+Inf    -0    1
+Inf     0    1
+Inf   1.2    1
+Inf  +Inf    0

func (*Float) Copy

func (z *Float) Copy(x *Float) *Float

Copy sets z to x, with the same precision, rounding mode, and accuracy as x, and returns z. x is not changed even if z and x are the same.

func (*Float) Float32

func (x *Float) Float32() (float32, Accuracy)

Float32 returns the float32 value nearest to x. If x is too small to be represented by a float32 (|x| < math.SmallestNonzeroFloat32), the result is (0, Below) or (-0, Above), respectively, depending on the sign of x. If x is too large to be represented by a float32 (|x| > math.MaxFloat32), the result is (+Inf, Above) or (-Inf, Below), depending on the sign of x.

func (*Float) Float64

func (x *Float) Float64() (float64, Accuracy)

Float64 returns the float64 value nearest to x. If x is too small to be represented by a float64 (|x| < math.SmallestNonzeroFloat64), the result is (0, Below) or (-0, Above), respectively, depending on the sign of x. If x is too large to be represented by a float64 (|x| > math.MaxFloat64), the result is (+Inf, Above) or (-Inf, Below), depending on the sign of x.

func (*Float) Format

func (x *Float) Format(format byte, prec int) string

Format converts the floating-point number x to a string according to the given format and precision prec. The format is one of:

'e'	-d.dddde±dd, decimal exponent, at least two (possibly 0) exponent digits
'E'	-d.ddddE±dd, decimal exponent, at least two (possibly 0) exponent digits
'f'	-ddddd.dddd, no exponent
'g'	like 'e' for large exponents, like 'f' otherwise
'G'	like 'E' for large exponents, like 'f' otherwise
'b'	-ddddddp±dd, binary exponent
'p'	-0x.dddp±dd, binary exponent, hexadecimal mantissa

For the binary exponent formats, the mantissa is printed in normalized form:

'b'	decimal integer mantissa using x.Prec() bits, or -0
'p'	hexadecimal fraction with 0.5 <= 0.mantissa < 1.0, or -0

The precision prec controls the number of digits (excluding the exponent) printed by the 'e', 'E', 'f', 'g', and 'G' formats. For 'e', 'E', and 'f' it is the number of digits after the decimal point. For 'g' and 'G' it is the total number of digits. A negative precision selects the smallest number of digits necessary such that ParseFloat will return f exactly. The prec value is ignored for the 'b' or 'p' format.

BUG(gri) Float.Format does not accept negative precisions.

func (*Float) Int

func (x *Float) Int(z *Int) (*Int, Accuracy)

Int returns the result of truncating x towards zero; or nil if x is an infinity. The result is Exact if x.IsInt(); otherwise it is Below for x > 0, and Above for x < 0. If a non-nil *Int argument z is provided, Int stores the result in z instead of allocating a new Int.

func (*Float) Int64

func (x *Float) Int64() (int64, Accuracy)

Int64 returns the integer resulting from truncating x towards zero. If math.MinInt64 <= x <= math.MaxInt64, the result is Exact if x is an integer, and Above (x < 0) or Below (x > 0) otherwise. The result is (math.MinInt64, Above) for x < math.MinInt64, and (math.MaxInt64, Below) for x > math.MaxInt64.

func (*Float) IsInf

func (x *Float) IsInf() bool

IsInf reports whether x is +Inf or -Inf.

func (*Float) IsInt

func (x *Float) IsInt() bool

IsInt reports whether x is an integer. ±Inf values are not integers.

func (*Float) MantExp

func (x *Float) MantExp(mant *Float) (exp int)

MantExp breaks x into its mantissa and exponent components and returns the exponent. If a non-nil mant argument is provided its value is set to the mantissa of x, with the same precision and rounding mode as x. The components satisfy x == mant × 2**exp, with 0.5 <= |mant| < 1.0. Calling MantExp with a nil argument is an efficient way to get the exponent of the receiver.

Special cases are:

(  ±0).MantExp(mant) = 0, with mant set to   ±0
(±Inf).MantExp(mant) = 0, with mant set to ±Inf

x and mant may be the same in which case x is set to its mantissa value.

func (*Float) MinPrec

func (x *Float) MinPrec() uint

MinPrec returns the minimum precision required to represent x exactly (i.e., the smallest prec before x.SetPrec(prec) would start rounding x). The result is 0 for |x| == 0 and |x| == Inf.

func (*Float) Mode

func (x *Float) Mode() RoundingMode

Mode returns the rounding mode of x.

func (*Float) Mul

func (z *Float) Mul(x, y *Float) *Float

Mul sets z to the rounded product x*y and returns z. Precision, rounding, and accuracy reporting are as for Add. Mul panics with ErrNaN if one operand is zero and the other operand an infinity. The value of z is undefined in that case.

func (*Float) Neg

func (z *Float) Neg(x *Float) *Float

Neg sets z to the (possibly rounded) value of x with its sign negated, and returns z.

func (*Float) Parse

func (z *Float) Parse(s string, base int) (f *Float, b int, err error)

Parse is like z.Scan(r, base), but instead of reading from an io.ByteScanner, it parses the string s. An error is also returned if the string contains invalid or trailing bytes not belonging to the number.

func (*Float) Prec

func (x *Float) Prec() uint

Prec returns the mantissa precision of x in bits. The result may be 0 for |x| == 0 and |x| == Inf.

func (*Float) Quo

func (z *Float) Quo(x, y *Float) *Float

Quo sets z to the rounded quotient x/y and returns z. Precision, rounding, and accuracy reporting are as for Add. Quo panics with ErrNaN if both operands are zero or infinities. The value of z is undefined in that case.

func (*Float) Rat

func (x *Float) Rat(z *Rat) (*Rat, Accuracy)

Rat returns the rational number corresponding to x; or nil if x is an infinity. The result is Exact is x is not an Inf. If a non-nil *Rat argument z is provided, Rat stores the result in z instead of allocating a new Rat.

func (*Float) Scan

func (z *Float) Scan(r io.ByteScanner, base int) (f *Float, b int, err error)

Scan scans the number corresponding to the longest possible prefix of r representing a floating-point number with a mantissa in the given conversion base (the exponent is always a decimal number). It sets z to the (possibly rounded) value of the corresponding floating-point number, and returns z, the actual base b, and an error err, if any. If z's precision is 0, it is changed to 64 before rounding takes effect. The number must be of the form:

	number   = [ sign ] [ prefix ] mantissa [ exponent ] .
	sign     = "+" | "-" .
     prefix   = "0" ( "x" | "X" | "b" | "B" ) .
	mantissa = digits | digits "." [ digits ] | "." digits .
	exponent = ( "E" | "e" | "p" ) [ sign ] digits .
	digits   = digit { digit } .
	digit    = "0" ... "9" | "a" ... "z" | "A" ... "Z" .

The base argument must be 0, 2, 10, or 16. Providing an invalid base argument will lead to a run-time panic.

For base 0, the number prefix determines the actual base: A prefix of "0x" or "0X" selects base 16, and a "0b" or "0B" prefix selects base 2; otherwise, the actual base is 10 and no prefix is accepted. The octal prefix "0" is not supported (a leading "0" is simply considered a "0").

A "p" exponent indicates a binary (rather then decimal) exponent; for instance "0x1.fffffffffffffp1023" (using base 0) represents the maximum float64 value. For hexadecimal mantissae, the exponent must be binary, if present (an "e" or "E" exponent indicator cannot be distinguished from a mantissa digit).

The returned *Float f is nil and the value of z is valid but not defined if an error is reported.

BUG(gri) The Float.Scan signature conflicts with Scan(s fmt.ScanState, ch rune) error.

func (*Float) Set

func (z *Float) Set(x *Float) *Float

Set sets z to the (possibly rounded) value of x and returns z. If z's precision is 0, it is changed to the precision of x before setting z (and rounding will have no effect). Rounding is performed according to z's precision and rounding mode; and z's accuracy reports the result error relative to the exact (not rounded) result.

func (*Float) SetFloat64

func (z *Float) SetFloat64(x float64) *Float

SetFloat64 sets z to the (possibly rounded) value of x and returns z. If z's precision is 0, it is changed to 53 (and rounding will have no effect). SetFloat64 panics with ErrNaN if x is a NaN.

func (*Float) SetInf

func (z *Float) SetInf(signbit bool) *Float

SetInf sets z to the infinite Float -Inf if signbit is set, or +Inf if signbit is not set, and returns z. The precision of z is unchanged and the result is always Exact.

func (*Float) SetInt

func (z *Float) SetInt(x *Int) *Float

SetInt sets z to the (possibly rounded) value of x and returns z. If z's precision is 0, it is changed to the larger of x.BitLen() or 64 (and rounding will have no effect).

func (*Float) SetInt64

func (z *Float) SetInt64(x int64) *Float

SetInt64 sets z to the (possibly rounded) value of x and returns z. If z's precision is 0, it is changed to 64 (and rounding will have no effect).

func (*Float) SetMantExp

func (z *Float) SetMantExp(mant *Float, exp int) *Float

SetMantExp sets z to mant × 2**exp and and returns z. The result z has the same precision and rounding mode as mant. SetMantExp is an inverse of MantExp but does not require 0.5 <= |mant| < 1.0. Specifically:

mant := new(Float)
new(Float).SetMantExp(mant, x.SetMantExp(mant)).Cmp(x).Eql() is true

Special cases are:

z.SetMantExp(  ±0, exp) =   ±0
z.SetMantExp(±Inf, exp) = ±Inf

z and mant may be the same in which case z's exponent is set to exp.

func (*Float) SetMode

func (z *Float) SetMode(mode RoundingMode) *Float

SetMode sets z's rounding mode to mode and returns an exact z. z remains unchanged otherwise. z.SetMode(z.Mode()) is a cheap way to set z's accuracy to Exact.

func (*Float) SetPrec

func (z *Float) SetPrec(prec uint) *Float

SetPrec sets z's precision to prec and returns the (possibly) rounded value of z. Rounding occurs according to z's rounding mode if the mantissa cannot be represented in prec bits without loss of precision. SetPrec(0) maps all finite values to ±0; infinite values remain unchanged. If prec > MaxPrec, it is set to MaxPrec.

func (*Float) SetRat

func (z *Float) SetRat(x *Rat) *Float

SetRat sets z to the (possibly rounded) value of x and returns z. If z's precision is 0, it is changed to the largest of a.BitLen(), b.BitLen(), or 64; with x = a/b.

func (*Float) SetString

func (z *Float) SetString(s string) (*Float, bool)

SetString sets z to the value of s and returns z and a boolean indicating success. s must be a floating-point number of the same format as accepted by Scan, with number prefixes permitted.

func (*Float) SetUint64

func (z *Float) SetUint64(x uint64) *Float

SetUint64 sets z to the (possibly rounded) value of x and returns z. If z's precision is 0, it is changed to 64 (and rounding will have no effect).

func (*Float) Sign

func (x *Float) Sign() int

Sign returns:

-1 if x <   0
 0 if x is ±0
+1 if x >   0

func (*Float) Signbit

func (x *Float) Signbit() bool

Signbit returns true if x is negative or negative zero.

func (*Float) String

func (x *Float) String() string

BUG(gri): Float.String uses x.Format('g', 10) rather than x.Format('g', -1).

func (*Float) Sub

func (z *Float) Sub(x, y *Float) *Float

Sub sets z to the rounded difference x-y and returns z. Precision, rounding, and accuracy reporting are as for Add. Sub panics with ErrNaN if x and y are infinities with equal signs. The value of z is undefined in that case.

func (*Float) Uint64

func (x *Float) Uint64() (uint64, Accuracy)

Uint64 returns the unsigned integer resulting from truncating x towards zero. If 0 <= x <= math.MaxUint64, the result is Exact if x is an integer and Below otherwise. The result is (0, Above) for x < 0, and (math.MaxUint64, Below) for x > math.MaxUint64.

type Int

type Int struct {
    // contains filtered or unexported fields
}

Int 表示一个带符号多精度整数。 Int 的零值为值 0。

func NewInt

func NewInt(x int64) *Int

NewInt 为 x 分配并返回一个新的 Int。

func (*Int) Abs

func (z *Int) Abs(x *Int) *Int

Abs 将 z 置为 |x|(即 x 的绝对值)并返回 z。

func (*Int) Add

func (z *Int) Add(x, y *Int) *Int

Add 将 z 置为 x+y 的和并返回 z。

func (*Int) And

func (z *Int) And(x, y *Int) *Int

And 置 z = x & y 并返回 z。

func (*Int) AndNot

func (z *Int) AndNot(x, y *Int) *Int

AndNot 置 z = x &^ y 并返回 z。

func (*Int) Binomial

func (z *Int) Binomial(n, k int64) *Int

Binomial 将 z 置为 (n, k) 的二项式系数并返回 z。

func (*Int) Bit

func (x *Int) Bit(i int) uint

Bit 返回 x 第 i 位的值。换言之,它返回 (x>>i)&1。位下标 i 必须 >= 0。

func (*Int) BitLen

func (x *Int) BitLen() int

BitLen 返回 z 的绝对值的位数长度。0 的位长为 0.

func (*Int) Bits

func (x *Int) Bits() []Word

Bits 提供了对 z 的原始访问(未经检查但很快)。它通过将其绝对值作为小端序的 Word 切片返回来实现。其结果与 x 共享同一底层数组。Bits 旨在支持此包外缺失的底层 Int 功能的实现,除此之外应尽量避免。

func (*Int) Bytes

func (x *Int) Bytes() []byte

Bytes 将 x 的绝对值作为大端序的字节切片返回。

func (*Int) Cmp

func (x *Int) Cmp(y *Int) (r int)

Cmp 比较 x 和 y 并返回:

若 x <  y 则为 -1
若 x == y 则为  0
若 x >  y 则为 +1

func (*Int) Div

func (z *Int) Div(x, y *Int) *Int

Div 在 y != 0 时,将 z 置为 x/y 的商并返回 z。 若 y == 0,就会产生一个除以零的运行时派错。 Div 实现了欧氏除法(与Go不同),更多详情见 DivMod。

func (*Int) DivMod

func (z *Int) DivMod(x, y, m *Int) (*Int, *Int)

DivMod 在 y != 0 时,将 z 置为 x 除以 y 的商,将 m 置为 x 取模 y 的模数并返回值对 (z, m)。 若 y == 0,就会产生一个除以零的运行时派错。

DivMod 实现了截断式除法和取模(与Go不同):

q = x div y // 使得
m = x - y*q // 其中
0 <= m < |q|

(详见 Raymond T. Boute,《函数 div 和 mod 的欧氏定义》以及《ACM编程语言与系统会议记录》 (TOPLAS),14(2):127-144, New York, NY, USA, 4/1992. ACM 出版社。) 截断式除法和取模(与Go相同)见 QuoRem。

func (*Int) Exp

func (z *Int) Exp(x, y, m *Int) *Int

Exp 置 z = x**y mod |m|(换言之,m 的符号被忽略),并返回 z。 若 y <=0,则其结果为 1,若 m == nil 或 m == 0,则 z = x**y。 见 Knuth《计算机程序设计艺术》,卷 2,章节 4.6.3。

func (*Int) Format

func (x *Int) Format(s fmt.State, ch rune)

Format is a support routine for fmt.Formatter. It accepts the formats 'b' (binary), 'o' (octal), 'd' (decimal), 'x' (lowercase hexadecimal), and 'X' (uppercase hexadecimal). Also supported are the full suite of package fmt's format verbs for integral types, including '+', '-', and ' ' for sign control, '#' for leading zero in octal and for hexadecimal, a leading "0x" or "0X" for "%#x" and "%#X" respectively, specification of minimum digits precision, output field width, space or zero padding, and left or right justification.

func (*Int) GCD

func (z *Int) GCD(x, y, a, b *Int) *Int

GCD 将 z 置为 a 和 b 的最大公约数,二者必须均 > 0,并返回 z。 若 x 或 y 非 nil,GCD 会设置 x 与 y 的值使得 z = a*x + b*y。 若 a 或 b <= 0,GCD就会置 z = x = y = 0。

func (*Int) GobDecode

func (z *Int) GobDecode(buf []byte) error

GobDecode 实现了 gob.GobDecoder 接口。

func (*Int) GobEncode

func (x *Int) GobEncode() ([]byte, error)

GobEncode 实现了 gob.GobEncoder 接口。

func (*Int) Int64

func (x *Int) Int64() int64

Int64 返回 x 的 int64 表示。 若 x 不能被表示为 int64,则其结果是未定义的。

func (*Int) Lsh

func (z *Int) Lsh(x *Int, n uint) *Int

Lsh 置 z = x << n 并返回 z。

func (*Int) MarshalJSON

func (z *Int) MarshalJSON() ([]byte, error)

MarshalJSON 实现了 json.Marshaler 接口。

func (*Int) MarshalText

func (z *Int) MarshalText() (text []byte, err error)

MarshalText implements the encoding.TextMarshaler interface.

func (*Int) Mod

func (z *Int) Mod(x, y *Int) *Int

Mod 在 y != 0 时,将 z 置为 x%y 的余数并返回 z。 若 y == 0,就会产生一个除以零的运行时派错。 Mod 实现了欧氏取模(与Go不同),更多详情见 DivMod。

func (*Int) ModInverse

func (z *Int) ModInverse(g, n *Int) *Int

ModInverse 将 z 置为 g 在环 ℤ/nℤ 中的乘法逆元素并返回 z。若 g 与 n 并不互质,则结果为未定义。

func (*Int) ModSqrt

func (z *Int) ModSqrt(x, p *Int) *Int

ModSqrt sets z to a square root of x mod p if such a square root exists, and returns z. The modulus p must be an odd prime. If x is not a square mod p, ModSqrt leaves z unchanged and returns nil. This function panics if p is not an odd integer.

func (*Int) Mul

func (z *Int) Mul(x, y *Int) *Int

Mul 将 z 置为 x*y 的积并返回 z。

func (*Int) MulRange

func (z *Int) MulRange(a, b int64) *Int

MulRange 将 z 置为闭区间 [a, b] 内所有整数的积并返回 z。 若 a > b(空区间),则其结果为 1。

func (*Int) Neg

func (z *Int) Neg(x *Int) *Int

Neg 将 z 置为 -x 并返回 z。

func (*Int) Not

func (z *Int) Not(x *Int) *Int

Not 置 z = ^x 并返回 z。

func (*Int) Or

func (z *Int) Or(x, y *Int) *Int

Or 置 z = x | y 并返回 z。

func (*Int) ProbablyPrime

func (x *Int) ProbablyPrime(n int) bool

ProbablyPrime 通过执行 n 次 Miller-Rabin 测试来检查 x 是否为质数。 若它返回 true,x 有 1 - 1/4^n 的可能性为质数。 若它返回 false,则 x 不是质数。n 必须 > 0。

func (*Int) Quo

func (z *Int) Quo(x, y *Int) *Int

Quo 在 y != 0 时,将 z 置为 x/y 的商并返回 z。 若 y == 0,就会产生一个除以零的运行时派错。 Quo 实现了截断式除法(与Go相同),更多详情见 QuoRem。

func (*Int) QuoRem

func (z *Int) QuoRem(x, y, r *Int) (*Int, *Int)

QuoRem 在 y != 0 时,将 z 置为 x/y 的商,将 r 置为 x%y 的余数并返回值对 (z, r)。 若 y == 0,就会产生一个除以零的运行时派错。

QuoRem 实现了截断式除法和取模(与Go相同):

q = x/y      // 其结果向零截断
r = x - y*q

(详见 Daan Leijen,《计算机科学家的除法和取模》。) 欧氏除法和取模(与Go不同)见 DivMod。

func (*Int) Rand

func (z *Int) Rand(rnd *rand.Rand, n *Int) *Int

Rand 将 z 置为区间 [0, n) 中的一个伪随机数并返回 z。

func (*Int) Rem

func (z *Int) Rem(x, y *Int) *Int

Rem 在 y != 0 时,将 z 置为 x%y 的余数并返回 z。 若 y == 0,就会产生一个除以零的运行时派错。 Rem 实现了截断式取模(与Go相同),更多详情见 QuoRem。

func (*Int) Rsh

func (z *Int) Rsh(x *Int, n uint) *Int

Rsh 置 z = x >> n 并返回 z。

func (*Int) Scan

func (z *Int) Scan(s fmt.ScanState, ch rune) error

Scan is a support routine for fmt.Scanner; it sets z to the value of the scanned number. It accepts the formats 'b' (binary), 'o' (octal), 'd' (decimal), 'x' (lowercase hexadecimal), and 'X' (uppercase hexadecimal).

示例

代码:

// 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)
}

输出:

18446744073709551617

func (*Int) Set

func (z *Int) Set(x *Int) *Int

Set 将 z 置为 x 并返回 z。

func (*Int) SetBit

func (z *Int) SetBit(x *Int, i int, b uint) *Int

SetBit 将 z 置为 x,将 x 的第 i 位置为 b(0 或 1)。 换言之,若 b 为 1,SetBit 会置 z = x | (1 << i);若 b 为 0,SetBit 会置 z = x &^ (1 << i)。若 b 非 0 或 1,SetBit 就会引发派错。

func (*Int) SetBits

func (z *Int) SetBits(abs []Word) *Int

SetBits 提供了对 z 的原始访问(未经检查但很快)。它通过将其值设为 abs,解释为小端序的 Word 切片,并返回 z 来实现。SetBits 旨在支持此包外缺失的底层 Int 功能的实现,除此之外应尽量避免。

func (*Int) SetBytes

func (z *Int) SetBytes(buf []byte) *Int

SetBytes 将 buf 解释为大端序的无符号整数字节,置 z 为该值后返回 z。

func (*Int) SetInt64

func (z *Int) SetInt64(x int64) *Int

SetInt64 将 z 置为 x 并返回 z。

func (*Int) SetString

func (z *Int) SetString(s string, base int) (*Int, bool)

SetString 将 z 置为 s 的值,按给定的进制 base 解释并返回 z 和一个指示是否成功的布尔值。 若 SetString 失败,则 z 的值是未定义的,其返回值则为 nil。

进制实参 base 必须为 0 或从 2 到 MaxBase 的值。若 base 为 0,则其实际的转换进制由 该字符串的前缀决定。前缀“0x”或“0X”会选择16进制,前缀“0”会选择8进制,前缀“0b”或“0B” 会选择2进制。其它情况则选择10进制。

示例

代码:

i := new(big.Int)
i.SetString("644", 8) // octal
fmt.Println(i)

输出:

420

func (*Int) SetUint64

func (z *Int) SetUint64(x uint64) *Int

SetUint64 将 z 置为 x 并返回 z。

func (*Int) Sign

func (x *Int) Sign() int

符号返回:

若 x <  0 则为 -1
若 x == 0 则为  0
若 x >  0 则为 +1

func (*Int) String

func (x *Int) String() string

func (*Int) Sub

func (z *Int) Sub(x, y *Int) *Int

Sub 将 z 置为 x-y 的差并返回 z。

func (*Int) Uint64

func (x *Int) Uint64() uint64

Uint64 返回 x 的 uint64 表示。 若 x 不能被表示为 uint64,则其结果是未定义的。

func (*Int) UnmarshalJSON

func (z *Int) UnmarshalJSON(text []byte) error

UnmarshalJSON 实现了 json.Unmarshaler 接口。

func (*Int) UnmarshalText

func (z *Int) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface.

func (*Int) Xor

func (z *Int) Xor(x, y *Int) *Int

Xor 置 z = x ^ y 并返回 z。

type Rat

type Rat struct {
    // contains filtered or unexported fields
}

A Rat represents a quotient a/b of arbitrary precision. The zero value for a Rat represents the value 0.

func NewRat

func NewRat(a, b int64) *Rat

NewRat creates a new Rat with numerator a and denominator b.

func (*Rat) Abs

func (z *Rat) Abs(x *Rat) *Rat

Abs sets z to |x| (the absolute value of x) and returns z.

func (*Rat) Add

func (z *Rat) Add(x, y *Rat) *Rat

Add sets z to the sum x+y and returns z.

func (*Rat) Cmp

func (x *Rat) Cmp(y *Rat) int

Cmp compares x and y and returns:

-1 if x <  y
 0 if x == y
+1 if x >  y

func (*Rat) Denom

func (x *Rat) Denom() *Int

Denom returns the denominator of x; it is always > 0. The result is a reference to x's denominator; it may change if a new value is assigned to x, and vice versa.

func (*Rat) Float32

func (x *Rat) Float32() (f float32, exact bool)

Float32 returns the nearest float32 value for x and a bool indicating whether f represents x exactly. If the magnitude of x is too large to be represented by a float32, f is an infinity and exact is false. The sign of f always matches the sign of x, even if f == 0.

func (*Rat) Float64

func (x *Rat) Float64() (f float64, exact bool)

Float64 returns the nearest float64 value for x and a bool indicating whether f represents x exactly. If the magnitude of x is too large to be represented by a float64, f is an infinity and exact is false. The sign of f always matches the sign of x, even if f == 0.

func (*Rat) FloatString

func (x *Rat) FloatString(prec int) string

FloatString returns a string representation of x in decimal form with prec digits of precision after the decimal point and the last digit rounded.

func (*Rat) GobDecode

func (z *Rat) GobDecode(buf []byte) error

GobDecode implements the gob.GobDecoder interface.

func (*Rat) GobEncode

func (x *Rat) GobEncode() ([]byte, error)

GobEncode implements the gob.GobEncoder interface.

func (*Rat) Inv

func (z *Rat) Inv(x *Rat) *Rat

Inv sets z to 1/x and returns z.

func (*Rat) IsInt

func (x *Rat) IsInt() bool

IsInt reports whether the denominator of x is 1.

func (*Rat) MarshalText

func (r *Rat) MarshalText() (text []byte, err error)

MarshalText implements the encoding.TextMarshaler interface.

func (*Rat) Mul

func (z *Rat) Mul(x, y *Rat) *Rat

Mul sets z to the product x*y and returns z.

func (*Rat) Neg

func (z *Rat) Neg(x *Rat) *Rat

Neg sets z to -x and returns z.

func (*Rat) Num

func (x *Rat) Num() *Int

Num returns the numerator of x; it may be <= 0. The result is a reference to x's numerator; it may change if a new value is assigned to x, and vice versa. The sign of the numerator corresponds to the sign of x.

func (*Rat) Quo

func (z *Rat) Quo(x, y *Rat) *Rat

Quo sets z to the quotient x/y and returns z. If y == 0, a division-by-zero run-time panic occurs.

func (*Rat) RatString

func (x *Rat) RatString() string

RatString returns a string representation of x in the form "a/b" if b != 1, and in the form "a" if b == 1.

func (*Rat) Scan

func (z *Rat) Scan(s fmt.ScanState, ch rune) error

Scan is a support routine for fmt.Scanner. It accepts the formats 'e', 'E', 'f', 'F', 'g', 'G', and 'v'. All formats are equivalent.

示例

代码:

// 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)
}

输出:

3/2

func (*Rat) Set

func (z *Rat) Set(x *Rat) *Rat

Set sets z to x (by making a copy of x) and returns z.

func (*Rat) SetFloat64

func (z *Rat) SetFloat64(f float64) *Rat

SetFloat64 sets z to exactly f and returns z. If f is not finite, SetFloat returns nil.

func (*Rat) SetFrac

func (z *Rat) SetFrac(a, b *Int) *Rat

SetFrac sets z to a/b and returns z.

func (*Rat) SetFrac64

func (z *Rat) SetFrac64(a, b int64) *Rat

SetFrac64 sets z to a/b and returns z.

func (*Rat) SetInt

func (z *Rat) SetInt(x *Int) *Rat

SetInt sets z to x (by making a copy of x) and returns z.

func (*Rat) SetInt64

func (z *Rat) SetInt64(x int64) *Rat

SetInt64 sets z to x and returns z.

func (*Rat) SetString

func (z *Rat) SetString(s string) (*Rat, bool)

SetString sets z to the value of s and returns z and a boolean indicating success. s can be given as a fraction "a/b" or as a floating-point number optionally followed by an exponent. If the operation failed, the value of z is undefined but the returned value is nil.

示例

代码:

r := new(big.Rat)
r.SetString("355/113")
fmt.Println(r.FloatString(3))

输出:

3.142

func (*Rat) Sign

func (x *Rat) Sign() int

Sign returns:

-1 if x <  0
 0 if x == 0
+1 if x >  0

func (*Rat) String

func (x *Rat) String() string

String returns a string representation of x in the form "a/b" (even if b == 1).

func (*Rat) Sub

func (z *Rat) Sub(x, y *Rat) *Rat

Sub sets z to the difference x-y and returns z.

func (*Rat) UnmarshalText

func (r *Rat) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface.

type RoundingMode

type RoundingMode byte

RoundingMode determines how a Float value is rounded to the desired precision. Rounding may change the Float value; the rounding error is described by the Float's Accuracy.

const (
    ToNearestEven RoundingMode = iota // == IEEE 754-2008 roundTiesToEven
    ToNearestAway                     // == IEEE 754-2008 roundTiesToAway
    ToZero                            // == IEEE 754-2008 roundTowardZero
    AwayFromZero                      // no IEEE 754-2008 equivalent
    ToNegativeInf                     // == IEEE 754-2008 roundTowardNegative
    ToPositiveInf                     // == IEEE 754-2008 roundTowardPositive
)

The following rounding modes are supported.

func (RoundingMode) String

func (i RoundingMode) String() string

type Word

type Word uintptr

Word 表示多精度无符号整数的单个数字。

Bugs