Movatterモバイル変換


[0]ホーム

URL:


big

packagestandard library
go1.26.0Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 10, 2026 License:BSD-3-ClauseImports:14Imported by:221,940

Details

Repository

cs.opensource.google/go/go

Links

Documentation

Overview

Package big implements arbitrary-precision arithmetic (big numbers).The following numeric types are supported:

Int    signed integersRat    rational numbersFloat  floating-point numbers

The zero value for anInt,Rat, orFloat correspond to 0. Thus, newvalues can be declared in the usual ways and denote 0 without furtherinitialization:

var x Int        // &x is an *Int of value 0var r = &Rat{}   // r is a *Rat of value 0y := new(Float)  // y is a *Float of value 0

Alternatively, new values can be allocated and initialized with factoryfunctions of the form:

func NewT(v V) *T

For instance,NewInt(x) returns an *Int set to the value of the int64argument x,NewRat(a, b) returns a *Rat set to the fraction a/b wherea and b are int64 values, andNewFloat(f) returns a *Float initializedto the float64 argument f. More flexibility is provided with explicitsetters, for instance:

var z1 Intz1.SetUint64(123)                 // z1 := 123z2 := new(Rat).SetFloat64(1.25)   // z2 := 5/4z3 := new(Float).SetInt(z1)       // z3 := 123.0

Setters, numeric operations and predicates are represented as methods ofthe form:

func (z *T) SetV(v V) *T          // z = vfunc (z *T) Unary(x *T) *T        // z = unary xfunc (z *T) Binary(x, y *T) *T    // z = x binary yfunc (x *T) Pred() P              // p = pred(x)

with T one ofInt,Rat, orFloat. For unary and binary operations, theresult is the receiver (usually named z in that case; see below); if itis one of the operands x or y it may be safely overwritten (and its memoryreused).

Arithmetic expressions are typically written as a sequence of individualmethod calls, with each call corresponding to an operation. The receiverdenotes the result and the method arguments are the operation's operands.For instance, given three *Int values a, b and c, the invocation

c.Add(a, b)

computes the sum a + b and stores the result in c, overwriting whatevervalue was held in c before. Unless specified otherwise, operations permitaliasing of parameters, so it is perfectly ok to write

sum.Add(sum, x)

to accumulate values x in a sum.

(By always passing in a result value via the receiver, memory use can bemuch better controlled. Instead of having to allocate new memory for eachresult, an operation can reuse the space allocated for the result value,and overwrite that value with the new result in the process.)

Notational convention: Incoming method parameters (including the receiver)are named consistently in the API to clarify their use. Incoming operandsare usually named x, y, a, b, and so on, but never z. A parameter specifyingthe result is named z (typically the receiver).

For instance, the arguments for (*Int).Add are named x and y, and becausethe receiver specifies the result destination, it is called z:

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

Methods of this form typically return the incoming receiver as well, toenable simple call chaining.

Methods which don't require a result value to be passed in (for instance,Int.Sign), simply return the result. In this case, the receiver is typicallythe first operand, named x:

func (x *Int) Sign() int

Various methods support conversions between strings and correspondingnumeric values, and vice versa: *Int, *Rat, and *Float values implementthe Stringer interface for a (default) string representation of the value,but also provide SetString methods to initialize a value from a string ina variety of supported formats (see the respective SetString documentation).

Finally, *Int, *Rat, and *Float satisfyfmt.Scanner for scanningand (except for *Rat) the Formatter interface for formatted printing.

Example (EConvergents)

This example demonstrates how to use big.Rat to compute thefirst 15 terms in the sequence of rational convergents forthe constant e (base of natural logarithm).

package mainimport ("fmt""math/big")// Use the classic continued fraction for e////e = [1; 0, 1, 1, 2, 1, 1, ... 2n, 1, 1, ...]//// i.e., for the nth term, use////   1          if   n mod 3 != 1//(n-1)/3 * 2   if   n mod 3 == 1func recur(n, lim int64) *big.Rat {term := new(big.Rat)if n%3 != 1 {term.SetInt64(1)} else {term.SetInt64((n - 1) / 3 * 2)}if n > lim {return term}// Directly initialize frac as the fractional// inverse of the result of recur.frac := new(big.Rat).Inv(recur(n+1, lim))return term.Add(term, frac)}// This example demonstrates how to use big.Rat to compute the// first 15 terms in the sequence of rational convergents for// the constant e (base of natural logarithm).func main() {for i := 1; i <= 15; i++ {r := recur(0, int64(i))// Print r both as a fraction and as a floating-point number.// Since big.Rat implements fmt.Formatter, we can use %-13s to// get a left-aligned string representation of the fraction.fmt.Printf("%-13s = %s\n", r, r.FloatString(8))}}
Output:2/1           = 2.000000003/1           = 3.000000008/3           = 2.6666666711/4          = 2.7500000019/7          = 2.7142857187/32         = 2.71875000106/39        = 2.71794872193/71        = 2.718309861264/465      = 2.718279571457/536      = 2.718283582721/1001     = 2.7182817223225/8544    = 2.7182818425946/9545    = 2.7182818249171/18089   = 2.71828183517656/190435 = 2.71828183

Example (Fibonacci)

This example demonstrates how to use big.Int to compute the smallestFibonacci number with 100 decimal digits and to test whether it is prime.

package mainimport ("fmt""math/big")func main() {// Initialize two big ints with the first two numbers in the sequence.a := big.NewInt(0)b := big.NewInt(1)// Initialize limit as 10^99, the smallest integer with 100 digits.var limit big.Intlimit.Exp(big.NewInt(10), big.NewInt(99), nil)// Loop while a is smaller than 1e100.for a.Cmp(&limit) < 0 {// Compute the next Fibonacci number, storing it in a.a.Add(a, b)// Swap a and b so that b is the next number in the sequence.a, b = b, a}fmt.Println(a) // 100-digit Fibonacci number// Test a for primality.// (ProbablyPrimes' argument sets the number of Miller-Rabin// rounds to be performed. 20 is a good value.)fmt.Println(a.ProbablyPrime(20))}
Output:1344719667586153181419716641724567886890850696275767987106294472017884974410332069524504824747437757false

Example (Sqrt2)

This example shows how to use big.Float to compute the square root of 2 witha precision of 200 bits, and how to print the result as a decimal number.

package mainimport ("fmt""math""math/big")func main() {// We'll do computations with 200 bits of precision in the mantissa.const prec = 200// Compute the square root of 2 using Newton's Method. We start with// an initial estimate for sqrt(2), and then iterate://     x_{n+1} = 1/2 * ( x_n + (2.0 / x_n) )// Since Newton's Method doubles the number of correct digits at each// iteration, we need at least log_2(prec) steps.steps := int(math.Log2(prec))// Initialize values we need for the computation.two := new(big.Float).SetPrec(prec).SetInt64(2)half := new(big.Float).SetPrec(prec).SetFloat64(0.5)// Use 1 as the initial estimate.x := new(big.Float).SetPrec(prec).SetInt64(1)// We use t as a temporary variable. There's no need to set its precision// since big.Float values with unset (== 0) precision automatically assume// the largest precision of the arguments when used as the result (receiver)// of a big.Float operation.t := new(big.Float)// Iterate.for i := 0; i <= steps; i++ {t.Quo(two, x)  // t = 2.0 / x_nt.Add(x, t)    // t = x_n + (2.0 / x_n)x.Mul(half, t) // x_{n+1} = 0.5 * t}// We can use the usual fmt.Printf verbs since big.Float implements fmt.Formatterfmt.Printf("sqrt(2) = %.50f\n", x)// Print the error between 2 and x*x.t.Mul(x, x) // t = x*xfmt.Printf("error = %e\n", t.Sub(two, t))}
Output:sqrt(2) = 1.41421356237309504880168872420969807856967187537695error = 0.000000e+00

Index

Examples

Constants

View Source
const (MaxExp  =math.MaxInt32// largest supported exponentMinExp  =math.MinInt32// smallest supported exponentMaxPrec =math.MaxUint32// largest (theoretically) supported precision; likely memory-limited)

Exponent and precision limits.

View Source
const MaxBase = 10 + ('z' - 'a' + 1) + ('Z' - 'A' + 1)

MaxBase is the largest number base accepted for string conversions.

Variables

This section is empty.

Functions

funcJacobiadded ingo1.5

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.

Types

typeAccuracyadded ingo1.5

type Accuracyint8

Accuracy describes the rounding error produced by the most recentoperation that generated aFloat value, relative to the exact value.

const (BelowAccuracy = -1ExactAccuracy = 0AboveAccuracy = +1)

Constants describing theAccuracy of aFloat.

func (Accuracy)Stringadded ingo1.5

func (iAccuracy) String()string

typeErrNaNadded ingo1.5

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

An ErrNaN panic is raised by aFloat operation that would lead toa NaN under IEEE 754 rules. An ErrNaN implements the error interface.

func (ErrNaN)Erroradded ingo1.5

func (errErrNaN) Error()string

typeFloatadded ingo1.5

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 yis 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 torepresent the value. The rounding mode specifies how a result shouldbe rounded to fit into the mantissa bits, and accuracy describes therounding error with respect to the exact result.

Unless specified otherwise, all operations (including setters) thatspecify a *Float variable for the result (usually via the receiverwith the exception ofFloat.MantExp), round the numeric result accordingto the precision and rounding mode of the result variable.

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

By setting the desired precision to 24 or 53 and using matching roundingmode (typicallyToNearestEven), Float operations produce the same resultsas the corresponding float32 or float64 IEEE 754 arithmetic for operandsthat correspond to normal (i.e., not denormal) float32 or float64 numbers.Exponent underflow and overflow lead to a 0 or an Infinity for differentvalues than IEEE 754 because Float exponents have a much larger range.

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

Operations always take pointer arguments (*Float) ratherthan Float values, and each unique Float value requiresits own unique *Float pointer. To "copy" a Float value,an existing (or newly allocated) Float must be set toa new value using theFloat.Set method; shallow copiesof Floats are not supported and may lead to errors.

Example (Shift)
package mainimport ("fmt""math/big")func main() {// Implement Float "shift" by modifying the (binary) exponents directly.for s := -5; s <= 5; s++ {x := big.NewFloat(0.5)x.SetMantExp(x, x.MantExp(nil)+s) // shift x by sfmt.Println(x)}}
Output:0.0156250.031250.06250.1250.250.5124816

funcNewFloatadded ingo1.5

func NewFloat(xfloat64) *Float

NewFloat allocates and returns a newFloat set to x,with precision 53 and rounding modeToNearestEven.NewFloat panics withErrNaN if x is a NaN.

funcParseFloatadded ingo1.5

func ParseFloat(sstring, baseint, precuint, modeRoundingMode) (f *Float, bint, errerror)

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

func (*Float)Absadded ingo1.5

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)Accadded ingo1.5

func (x *Float) Acc()Accuracy

Acc returns the accuracy of x produced by the most recentoperation, unless explicitly documented otherwise by thatoperation.

func (*Float)Addadded ingo1.5

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; andz's accuracy reports the result error relative to the exact (not rounded)result. Add panics withErrNaN if x and y are infinities with oppositesigns. The value of z is undefined in that case.

Example
package mainimport ("fmt""math/big")func main() {// Operate on numbers of different precision.var x, y, z big.Floatx.SetInt64(1000)          // x is automatically set to 64bit precisiony.SetFloat64(2.718281828) // y is automatically set to 53bit precisionz.SetPrec(32)z.Add(&x, &y)fmt.Printf("x = %.10g (%s, prec = %d, acc = %s)\n", &x, x.Text('p', 0), x.Prec(), x.Acc())fmt.Printf("y = %.10g (%s, prec = %d, acc = %s)\n", &y, y.Text('p', 0), y.Prec(), y.Acc())fmt.Printf("z = %.10g (%s, prec = %d, acc = %s)\n", &z, z.Text('p', 0), z.Prec(), z.Acc())}
Output:x = 1000 (0x.fap+10, prec = 64, acc = Exact)y = 2.718281828 (0x.adf85458248cd8p+2, prec = 53, acc = Exact)z = 1002.718282 (0x.faadf854p+10, prec = 32, acc = Below)

func (*Float)Appendadded ingo1.5

func (x *Float) Append(buf []byte, fmtbyte, precint) []byte

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

func (*Float)AppendTextadded ingo1.24.0

func (x *Float) AppendText(b []byte) ([]byte,error)

AppendText implements theencoding.TextAppender interface.Only theFloat value is marshaled (in full precision), otherattributes such as precision or accuracy are ignored.

func (*Float)Cmpadded ingo1.5

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.
Example
package mainimport ("fmt""math""math/big")func main() {inf := math.Inf(1)zero := 0.0operands := []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("%4g  %4g  %3d\n", x, y, x.Cmp(y))}fmt.Println()}}
Output:   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)Copyadded ingo1.5

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

Copy sets z to x, with the same precision, rounding mode, and accuracy as x.Copy returns z. If x and z are identical, Copy is a no-op.

Example
package mainimport ("fmt""math/big")func main() {var x, z big.Floatx.SetFloat64(1.23)r := z.Copy(&x)fmt.Printf("a) r = %g, z = %g, x = %g, r == z = %v\n", r, &z, &x, r == &z)// changing z changes r since they are identicalz.SetInt64(42)fmt.Printf("b) r = %g, z = %g, r == z = %v\n", r, &z, r == &z)x.SetPrec(1)z.Copy(&x)fmt.Printf("c) z = %g, x = %g, z == x = %v\n", &z, &x, &z == &x)}
Output:a) r = 1.23, z = 1.23, x = 1.23, r == z = trueb) r = 42, z = 42, r == z = truec) z = 1, x = 1, z == x = false

func (*Float)Float32added ingo1.5

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

Float32 returns the float32 value nearest to x. If x is too small to berepresented by a float32 (|x| <math.SmallestNonzeroFloat32), the resultis (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)Float64added ingo1.5

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

Float64 returns the float64 value nearest to x. If x is too small to berepresented by a float64 (|x| <math.SmallestNonzeroFloat64), the resultis (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)Formatadded ingo1.5

func (x *Float) Format(sfmt.State, formatrune)

Format implementsfmt.Formatter. It accepts all the regularformats for floating-point numbers ('b', 'e', 'E', 'f', 'F','g', 'G', 'x') as well as 'p' and 'v'. See (*Float).Text for theinterpretation of 'p'. The 'v' format is handled like 'g'.Format also supports specification of the minimum precisionin digits, the output field width, as well as the format flags'+' and ' ' for sign control, '0' for space or zero padding,and '-' for left or right justification. See the fmt packagefor details.

func (*Float)GobDecodeadded ingo1.7

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

GobDecode implements theencoding/gob.GobDecoder interface.The result is rounded per the precision and rounding mode ofz unless z's precision is 0, in which case z is set exactlyto the decoded value.

func (*Float)GobEncodeadded ingo1.7

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

GobEncode implements theencoding/gob.GobEncoder interface.TheFloat value and all its attributes (precision,rounding mode, accuracy) are marshaled.

func (*Float)Intadded ingo1.5

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 isExact if x.IsInt(); otherwise it isBelowfor x > 0, andAbove for x < 0.If a non-nil *Int argument z is provided,Int storesthe result in z instead of allocating a newInt.

func (*Float)Int64added ingo1.5

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

Int64 returns the integer resulting from truncating x towards zero.Ifmath.MinInt64 <= x <=math.MaxInt64, the result isExact if x isan integer, andAbove (x < 0) orBelow (x > 0) otherwise.The result is (math.MinInt64,Above) for x <math.MinInt64,and (math.MaxInt64,Below) for x >math.MaxInt64.

func (*Float)IsInfadded ingo1.5

func (x *Float) IsInf()bool

IsInf reports whether x is +Inf or -Inf.

func (*Float)IsIntadded ingo1.5

func (x *Float) IsInt()bool

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

func (*Float)MantExpadded ingo1.5

func (x *Float) MantExp(mant *Float) (expint)

MantExp breaks x into its mantissa and exponent componentsand returns the exponent. If a non-nil mant argument isprovided its value is set to the mantissa of x, with thesame precision and rounding mode as x. The componentssatisfy x == mant × 2**exp, with 0.5 <= |mant| < 1.0.Calling MantExp with a nil argument is an efficient way toget 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 itsmantissa value.

func (*Float)MarshalTextadded ingo1.6

func (x *Float) MarshalText() (text []byte, errerror)

MarshalText implements theencoding.TextMarshaler interface.Only theFloat value is marshaled (in full precision), otherattributes such as precision or accuracy are ignored.

func (*Float)MinPrecadded ingo1.5

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)Modeadded ingo1.5

func (x *Float) Mode()RoundingMode

Mode returns the rounding mode of x.

func (*Float)Muladded ingo1.5

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 forFloat.Add.Mul panics withErrNaN if one operand is zero and the otheroperand an infinity. The value of z is undefined in that case.

func (*Float)Negadded ingo1.5

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)Parseadded ingo1.5

func (z *Float) Parse(sstring, baseint) (f *Float, bint, errerror)

Parse parses s which must contain a text representation of a floating-point number with a mantissa in the given conversion base (the exponentis always a decimal number), or a string representing an infinite value.

For base 0, an underscore character “_” may appear between a baseprefix and an adjacent digit, and between successive digits; suchunderscores do not change the value of the number, or the returneddigit count. Incorrect placement of underscores is reported as anerror if there are no other errors. If base != 0, underscores arenot recognized and thus terminate scanning like any other characterthat is not a valid radix point or digit.

It sets z to the (possibly rounded) value of the corresponding floating-point value, and returns z, the actual base b, and an error err, if any.The entire string (not just a prefix) must be consumed for success.If z's precision is 0, it is changed to 64 before rounding takes effect.The number must be of the form:

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

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

For base 0, the number prefix determines the actual base: A prefix of“0b” or “0B” selects base 2, “0o” or “0O” selects base 8, and“0x” or “0X” selects base 16. Otherwise, the actual base is 10 andno prefix is accepted. The octal prefix "0" is not supported (a leading"0" is simply considered a "0").

A "p" or "P" exponent indicates a base 2 (rather than base 10) exponent;for instance, "0x1.fffffffffffffp1023" (using base 0) represents themaximum float64 value. For hexadecimal mantissae, the exponent charactermust be one of 'p' or 'P', if present (an "e" or "E" exponent indicatorcannot be distinguished from a mantissa digit).

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

func (*Float)Precadded ingo1.5

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)Quoadded ingo1.5

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 forFloat.Add.Quo panics withErrNaN if both operands are zero or infinities.The value of z is undefined in that case.

func (*Float)Ratadded ingo1.5

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 isExact if x is not an Inf.If a non-nil *Rat argument z is provided,Rat storesthe result in z instead of allocating a newRat.

func (*Float)Scanadded ingo1.8

func (z *Float) Scan(sfmt.ScanState, chrune)error

Scan is a support routine forfmt.Scanner; it sets z to the value ofthe scanned number. It accepts formats whose verbs are supported byfmt.Scan for floating point values, which are:'b' (binary), 'e', 'E', 'f', 'F', 'g' and 'G'.Scan doesn't handle ±Inf.

Example
package mainimport ("fmt""log""math/big")func main() {// The Scan function is rarely used directly;// the fmt package recognizes it as an implementation of fmt.Scanner.f := new(big.Float)_, err := fmt.Sscan("1.19282e99", f)if err != nil {log.Println("error scanning value:", err)} else {fmt.Println(f)}}
Output:1.19282e+99

func (*Float)Setadded ingo1.5

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 xbefore setting z (and rounding will have no effect).Rounding is performed according to z's precision and roundingmode; and z's accuracy reports the result error relative to theexact (not rounded) result.

func (*Float)SetFloat64added ingo1.5

func (z *Float) SetFloat64(xfloat64) *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 haveno effect). SetFloat64 panics withErrNaN if x is a NaN.

func (*Float)SetInfadded ingo1.5

func (z *Float) SetInf(signbitbool) *Float

SetInf sets z to the infinite Float -Inf if signbit isset, or +Inf if signbit is not set, and returns z. Theprecision of z is unchanged and the result is alwaysExact.

func (*Float)SetIntadded ingo1.5

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)SetInt64added ingo1.5

func (z *Float) SetInt64(xint64) *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 haveno effect).

func (*Float)SetMantExpadded ingo1.5

func (z *Float) SetMantExp(mant *Float, expint) *Float

SetMantExp sets z to mant × 2**exp and returns z.The result z has the same precision and rounding modeas mant. SetMantExp is an inverse ofFloat.MantExp but doesnot require 0.5 <= |mant| < 1.0. Specifically, for agiven x of type *Float, SetMantExp relates toFloat.MantExpas follows:

mant := new(Float)new(Float).SetMantExp(mant, x.MantExp(mant)).Cmp(x) == 0

Special cases are:

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

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

func (*Float)SetModeadded ingo1.5

func (z *Float) SetMode(modeRoundingMode) *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 toExact.

func (*Float)SetPrecadded ingo1.5

func (z *Float) SetPrec(precuint) *Float

SetPrec sets z's precision to prec and returns the (possibly) roundedvalue of z. Rounding occurs according to z's rounding mode if the mantissacannot 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 toMaxPrec.

func (*Float)SetRatadded ingo1.5

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)SetStringadded ingo1.5

func (z *Float) SetString(sstring) (*Float,bool)

SetString sets z to the value of s and returns z and a boolean indicatingsuccess. s must be a floating-point number of the same format as acceptedbyFloat.Parse, with base argument 0. The entire string (not just a prefix) mustbe valid for success. If the operation failed, the value of z is undefinedbut the returned value is nil.

Example
package mainimport ("fmt""math/big")func main() {f := new(big.Float)f.SetString("3.14159")fmt.Println(f)}
Output:3.14159

func (*Float)SetUint64added ingo1.5

func (z *Float) SetUint64(xuint64) *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 haveno effect).

func (*Float)Signadded ingo1.5

func (x *Float) Sign()int

Sign returns:

  • -1 if x < 0;
  • 0 if x is ±0;
  • +1 if x > 0.

func (*Float)Signbitadded ingo1.5

func (x *Float) Signbit()bool

Signbit reports whether x is negative or negative zero.

func (*Float)Sqrtadded ingo1.10

func (z *Float) Sqrt(x *Float) *Float

Sqrt sets z to the rounded square root of x, and returns it.

If z's precision is 0, it is changed to x's precision before theoperation. Rounding is performed according to z's precision androunding mode, but z's accuracy is not computed. Specifically, theresult of z.Acc() is undefined.

The function panics if z < 0. The value of z is undefined in thatcase.

func (*Float)Stringadded ingo1.5

func (x *Float) String()string

String formats x like x.Text('g', 10).(String must be called explicitly,Float.Format does not support %s verb.)

func (*Float)Subadded ingo1.5

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 forFloat.Add.Sub panics withErrNaN if x and y are infinities with equalsigns. The value of z is undefined in that case.

func (*Float)Textadded ingo1.5

func (x *Float) Text(formatbyte, precint)string

Text converts the floating-point number x to a string accordingto 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'x'-0xd.dddddp±dd, hexadecimal mantissa, decimal power of two exponent'p'-0x.dddp±dd, hexadecimal mantissa, decimal power of two exponent (non-standard)'b'-ddddddp±dd, decimal mantissa, decimal power of two exponent (non-standard)

For the power-of-two exponent formats, the mantissa is printed in normalized form:

'x'hexadecimal mantissa in [1, 2), or 0'p'hexadecimal mantissa in [½, 1), or 0'b'decimal integer mantissa using x.Prec() bits, or 0

Note that the 'x' form is the one used by most other languages and libraries.

If format is a different character, Text returns a "%" followed by theunrecognized format character.

The precision prec controls the number of digits (excluding the exponent)printed by the 'e', 'E', 'f', 'g', 'G', and 'x' formats.For 'e', 'E', 'f', and 'x', it is the number of digits after the decimal point.For 'g' and 'G' it is the total number of digits. A negative precision selectsthe smallest number of decimal digits necessary to identify the value x uniquelyusing x.Prec() mantissa bits.The prec value is ignored for the 'b' and 'p' formats.

func (*Float)Uint64added ingo1.5

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

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

func (*Float)UnmarshalTextadded ingo1.6

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

UnmarshalText implements theencoding.TextUnmarshaler interface.The result is rounded per the precision and rounding mode of z.If z's precision is 0, it is changed to 64 before rounding takeseffect.

typeInt

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

An Int represents a signed multi-precision integer.The zero value for an Int represents the value 0.

Operations always take pointer arguments (*Int) ratherthan Int values, and each unique Int value requiresits own unique *Int pointer. To "copy" an Int value,an existing (or newly allocated) Int must be set toa new value using theInt.Set method; shallow copiesof Ints are not supported and may lead to errors.

Note that methods may leak the Int's value through timing side-channels.Because of this and because of the scope and complexity of theimplementation, Int is not well-suited to implement cryptographic operations.The standard library avoids exposing non-trivial Int methods toattacker-controlled inputs and the determination of whether a bug in math/bigis considered a security vulnerability might depend on the impact on thestandard library.

funcNewInt

func NewInt(xint64) *Int

NewInt allocates and returns a newInt set to x.

func (*Int)Abs

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

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

func (*Int)Add

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

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

func (*Int)And

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

And sets z = x & y and returns z.

func (*Int)AndNot

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

AndNot sets z = x &^ y and returns z.

func (*Int)Appendadded ingo1.6

func (x *Int) Append(buf []byte, baseint) []byte

Append appends the string representation of x, as generated byx.Text(base), to buf and returns the extended buffer.

func (*Int)AppendTextadded ingo1.24.0

func (x *Int) AppendText(b []byte) (text []byte, errerror)

AppendText implements theencoding.TextAppender interface.

func (*Int)Binomial

func (z *Int) Binomial(n, kint64) *Int

Binomial sets z to the binomial coefficient C(n, k) and returns z.

func (*Int)Bit

func (x *Int) Bit(iint)uint

Bit returns the value of the i'th bit of x. That is, itreturns (x>>i)&1. The bit index i must be >= 0.

func (*Int)BitLen

func (x *Int) BitLen()int

BitLen returns the length of the absolute value of x in bits.The bit length of 0 is 0.

func (*Int)Bits

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

Bits provides raw (unchecked but fast) access to x by returning itsabsolute value as a little-endianWord slice. The result and x sharethe same underlying array.Bits is intended to support implementation of missing low-levelIntfunctionality outside this package; it should be avoided otherwise.

func (*Int)Bytes

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

Bytes returns the absolute value of x as a big-endian byte slice.

To use a fixed length slice, or a preallocated one, useInt.FillBytes.

func (*Int)Cmp

func (x *Int) Cmp(y *Int) (rint)

Cmp compares x and y and returns:

  • -1 if x < y;
  • 0 if x == y;
  • +1 if x > y.

func (*Int)CmpAbsadded ingo1.10

func (x *Int) CmpAbs(y *Int)int

CmpAbs compares the absolute values of x and y and returns:

  • -1 if |x| < |y|;
  • 0 if |x| == |y|;
  • +1 if |x| > |y|.

func (*Int)Div

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

Div sets z to the quotient x/y for y != 0 and returns z.If y == 0, a division-by-zero run-time panic occurs.Div implements Euclidean division (unlike Go); seeInt.DivMod for more details.

func (*Int)DivMod

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

DivMod sets z to the quotient x div y and m to the modulus x mod yand returns the pair (z, m) for y != 0.If y == 0, a division-by-zero run-time panic occurs.

DivMod implements Euclidean division and modulus (unlike Go):

q = x div y  such thatm = x - y*q  with 0 <= m < |y|

(See Raymond T. Boute, “The Euclidean definition of the functionsdiv and mod”. ACM Transactions on Programming Languages andSystems (TOPLAS), 14(2):127-144, New York, NY, USA, 4/1992.ACM press.)SeeInt.QuoRem for T-division and modulus (like Go).

func (*Int)Exp

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

Exp sets z = x**y mod |m| (i.e. the sign of m is ignored), and returns z.If m == nil or m == 0, z = x**y unless y <= 0 then z = 1. If m != 0, y < 0,and x and m are not relatively prime, z is unchanged and nil is returned.

Modular exponentiation of inputs of a particular size is not acryptographically constant-time operation.

func (*Int)FillBytesadded ingo1.15

func (x *Int) FillBytes(buf []byte) []byte

FillBytes sets buf to the absolute value of x, storing it as a zero-extendedbig-endian byte slice, and returns buf.

If the absolute value of x doesn't fit in buf, FillBytes will panic.

func (*Int)Float64added ingo1.21.0

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

Float64 returns the float64 value nearest x,and an indication of any rounding that occurred.

func (*Int)Format

func (x *Int) Format(sfmt.State, chrune)

Format implementsfmt.Formatter. It accepts the formats'b' (binary), 'o' (octal with 0 prefix), 'O' (octal with 0o prefix),'d' (decimal), 'x' (lowercase hexadecimal), and'X' (uppercase hexadecimal).Also supported are the full suite of package fmt's formatflags for integral types, including '+' and ' ' for signcontrol, '#' for leading zero in octal and for hexadecimal,a leading "0x" or "0X" for "%#x" and "%#X" respectively,specification of minimum digits precision, output fieldwidth, space or zero padding, and '-' for left or rightjustification.

func (*Int)GCD

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

GCD sets z to the greatest common divisor of a and b and returns z.If x or y are not nil, GCD sets their value such that z = a*x + b*y.

a and b may be positive, zero or negative. (Before Go 1.14 both hadto be > 0.) Regardless of the signs of a and b, z is always >= 0.

If a == b == 0, GCD sets z = x = y = 0.

If a == 0 and b != 0, GCD sets z = |b|, x = 0, y = sign(b) * 1.

If a != 0 and b == 0, GCD sets z = |a|, x = sign(a) * 1, y = 0.

func (*Int)GobDecode

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

GobDecode implements theencoding/gob.GobDecoder interface.

func (*Int)GobEncode

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

GobEncode implements theencoding/gob.GobEncoder interface.

func (*Int)Int64

func (x *Int) Int64()int64

Int64 returns the int64 representation of x.If x cannot be represented in an int64, the result is undefined.

func (*Int)IsInt64added ingo1.9

func (x *Int) IsInt64()bool

IsInt64 reports whether x can be represented as an int64.

func (*Int)IsUint64added ingo1.9

func (x *Int) IsUint64()bool

IsUint64 reports whether x can be represented as a uint64.

func (*Int)Lsh

func (z *Int) Lsh(x *Int, nuint) *Int

Lsh sets z = x << n and returns z.

func (*Int)MarshalJSONadded ingo1.1

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

MarshalJSON implements theencoding/json.Marshaler interface.

func (*Int)MarshalTextadded ingo1.3

func (x *Int) MarshalText() (text []byte, errerror)

MarshalText implements theencoding.TextMarshaler interface.

func (*Int)Mod

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

Mod sets z to the modulus x%y for y != 0 and returns z.If y == 0, a division-by-zero run-time panic occurs.Mod implements Euclidean modulus (unlike Go); seeInt.DivMod for more details.

func (*Int)ModInverse

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

ModInverse sets z to the multiplicative inverse of g in the ring ℤ/nℤand returns z. If g and n are not relatively prime, g has no multiplicativeinverse in the ring ℤ/nℤ. In this case, z is unchanged and the return valueis nil. If n == 0, a division-by-zero run-time panic occurs.

func (*Int)ModSqrtadded ingo1.5

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, andreturns 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 isnot an odd integer, its behavior is undefined if p is odd but not prime.

func (*Int)Mul

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

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

func (*Int)MulRange

func (z *Int) MulRange(a, bint64) *Int

MulRange sets z to the product of all integersin the range [a, b] inclusively and returns z.If a > b (empty range), the result is 1.

func (*Int)Neg

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

Neg sets z to -x and returns z.

func (*Int)Not

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

Not sets z = ^x and returns z.

func (*Int)Or

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

Or sets z = x | y and returns z.

func (*Int)ProbablyPrime

func (x *Int) ProbablyPrime(nint)bool

ProbablyPrime reports whether x is probably prime,applying the Miller-Rabin test with n pseudorandomly chosen basesas well as a Baillie-PSW test.

If x is prime, ProbablyPrime returns true.If x is chosen randomly and not prime, ProbablyPrime probably returns false.The probability of returning true for a randomly chosen non-prime is at most ¼ⁿ.

ProbablyPrime is 100% accurate for inputs less than 2⁶⁴.See Menezes et al., Handbook of Applied Cryptography, 1997, pp. 145-149,and FIPS 186-4 Appendix F for further discussion of the error probabilities.

ProbablyPrime is not suitable for judging primes that an adversary mayhave crafted to fool the test.

As of Go 1.8, ProbablyPrime(0) is allowed and applies only a Baillie-PSW test.Before Go 1.8, ProbablyPrime applied only the Miller-Rabin tests, and ProbablyPrime(0) panicked.

func (*Int)Quo

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

Quo sets z to the quotient x/y for y != 0 and returns z.If y == 0, a division-by-zero run-time panic occurs.Quo implements truncated division (like Go); seeInt.QuoRem for more details.

func (*Int)QuoRem

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

QuoRem sets z to the quotient x/y and r to the remainder x%yand returns the pair (z, r) for y != 0.If y == 0, a division-by-zero run-time panic occurs.

QuoRem implements T-division and modulus (like Go):

q = x/y      with the result truncated to zeror = x - y*q

(See Daan Leijen, “Division and Modulus for Computer Scientists”.)SeeInt.DivMod for Euclidean division and modulus (unlike Go).

func (*Int)Rand

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

Rand sets z to a pseudo-random number in [0, n) and returns z.

As this uses themath/rand package, it must not be used forsecurity-sensitive work. Usecrypto/rand.Int instead.

func (*Int)Rem

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

Rem sets z to the remainder x%y for y != 0 and returns z.If y == 0, a division-by-zero run-time panic occurs.Rem implements truncated modulus (like Go); seeInt.QuoRem for more details.

func (*Int)Rsh

func (z *Int) Rsh(x *Int, nuint) *Int

Rsh sets z = x >> n and returns z.

func (*Int)Scan

func (z *Int) Scan(sfmt.ScanState, chrune)error

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

Example
package mainimport ("fmt""log""math/big")func main() {// 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

func (*Int)Set

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

Set sets z to x and returns z.

func (*Int)SetBit

func (z *Int) SetBit(x *Int, iint, buint) *Int

SetBit sets z to x, with x's i'th bit set to b (0 or 1).That is,

  • if b is 1, SetBit sets z = x | (1 << i);
  • if b is 0, SetBit sets z = x &^ (1 << i);
  • if b is not 0 or 1, SetBit will panic.

func (*Int)SetBits

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

SetBits provides raw (unchecked but fast) access to z by setting itsvalue to abs, interpreted as a little-endianWord slice, and returningz. The result and abs share the same underlying array.SetBits is intended to support implementation of missing low-levelIntfunctionality outside this package; it should be avoided otherwise.

func (*Int)SetBytes

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

SetBytes interprets buf as the bytes of a big-endian unsignedinteger, sets z to that value, and returns z.

func (*Int)SetInt64

func (z *Int) SetInt64(xint64) *Int

SetInt64 sets z to x and returns z.

func (*Int)SetString

func (z *Int) SetString(sstring, baseint) (*Int,bool)

SetString sets z to the value of s, interpreted in the given base,and returns z and a boolean indicating success. The entire string(not just a prefix) must be valid for success. If SetString fails,the value of z is undefined but the returned value is nil.

The base argument must be 0 or a value between 2 andMaxBase.For base 0, the number prefix determines the actual base: A prefix of“0b” or “0B” selects base 2, “0”, “0o” or “0O” selects base 8,and “0x” or “0X” selects base 16. Otherwise, the selected base is 10and no prefix is accepted.

For bases <= 36, lower and upper case letters are considered the same:The letters 'a' to 'z' and 'A' to 'Z' represent digit values 10 to 35.For bases > 36, the upper case letters 'A' to 'Z' represent the digitvalues 36 to 61.

For base 0, an underscore character “_” may appear between a baseprefix and an adjacent digit, and between successive digits; suchunderscores do not change the value of the number.Incorrect placement of underscores is reported as an error if thereare no other errors. If base != 0, underscores are not recognizedand act like any other character that is not a valid digit.

Example
package mainimport ("fmt""math/big")func main() {i := new(big.Int)i.SetString("644", 8) // octalfmt.Println(i)}
Output:420

func (*Int)SetUint64added ingo1.1

func (z *Int) SetUint64(xuint64) *Int

SetUint64 sets z to x and returns z.

func (*Int)Sign

func (x *Int) Sign()int

Sign returns:

  • -1 if x < 0;
  • 0 if x == 0;
  • +1 if x > 0.

func (*Int)Sqrtadded ingo1.8

func (z *Int) Sqrt(x *Int) *Int

Sqrt sets z to ⌊√x⌋, the largest integer such that z² ≤ x, and returns z.It panics if x is negative.

func (*Int)String

func (x *Int) String()string

String returns the decimal representation of x as generated byx.Text(10).

func (*Int)Sub

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

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

func (*Int)Textadded ingo1.6

func (x *Int) Text(baseint)string

Text returns the string representation of x in the given base.Base must be between 2 and 62, inclusive. The result uses thelower-case letters 'a' to 'z' for digit values 10 to 35, andthe upper-case letters 'A' to 'Z' for digit values 36 to 61.No prefix (such as "0x") is added to the string. If x is a nilpointer it returns "<nil>".

func (*Int)TrailingZeroBitsadded ingo1.13

func (x *Int) TrailingZeroBits()uint

TrailingZeroBits returns the number of consecutive least significant zerobits of |x|.

func (*Int)Uint64added ingo1.1

func (x *Int) Uint64()uint64

Uint64 returns the uint64 representation of x.If x cannot be represented in a uint64, the result is undefined.

func (*Int)UnmarshalJSONadded ingo1.1

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

UnmarshalJSON implements theencoding/json.Unmarshaler interface.

func (*Int)UnmarshalTextadded ingo1.3

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

UnmarshalText implements theencoding.TextUnmarshaler interface.

func (*Int)Xor

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

Xor sets z = x ^ y and returns z.

typeRat

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.

Operations always take pointer arguments (*Rat) ratherthan Rat values, and each unique Rat value requiresits own unique *Rat pointer. To "copy" a Rat value,an existing (or newly allocated) Rat must be set toa new value using theRat.Set method; shallow copiesof Rats are not supported and may lead to errors.

funcNewRat

func NewRat(a, bint64) *Rat

NewRat creates a newRat 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)AppendTextadded ingo1.24.0

func (x *Rat) AppendText(b []byte) ([]byte,error)

AppendText implements theencoding.TextAppender interface.

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, unlessx is an uninitialized (zero value)Rat, in which casethe result is a newInt of value 1. (To initialize x,any operation that sets x will do, including x.Set(x).)If the result is a reference to x's denominator itmay change if a new value is assigned to x, and vice versa.

func (*Rat)Float32added ingo1.4

func (x *Rat) Float32() (ffloat32, exactbool)

Float32 returns the nearest float32 value for x and a bool indicatingwhether f represents x exactly. If the magnitude of x is too large tobe 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)Float64added ingo1.1

func (x *Rat) Float64() (ffloat64, exactbool)

Float64 returns the nearest float64 value for x and a bool indicatingwhether f represents x exactly. If the magnitude of x is too large tobe 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)FloatPrecadded ingo1.22.0

func (x *Rat) FloatPrec() (nint, exactbool)

FloatPrec returns the number n of non-repeating digits immediatelyfollowing the decimal point of the decimal representation of x.The boolean result indicates whether a decimal representation of xwith that many fractional digits is exact or rounded.

Examples:

x      n    exact    decimal representation n fractional digits0      0    true     01      0    true     11/2    1    true     0.51/3    0    false    0       (0.333... rounded)1/4    2    true     0.251/6    1    false    0.2     (0.166... rounded)

func (*Rat)FloatString

func (x *Rat) FloatString(precint)string

FloatString returns a string representation of x in decimal form with precdigits of precision after the radix point. The last digit is rounded tonearest, with halves rounded away from zero.

func (*Rat)GobDecode

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

GobDecode implements theencoding/gob.GobDecoder interface.

func (*Rat)GobEncode

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

GobEncode implements theencoding/gob.GobEncoder interface.

func (*Rat)Inv

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

Inv sets z to 1/x and returns z.If x == 0, Inv panics.

func (*Rat)IsInt

func (x *Rat) IsInt()bool

IsInt reports whether the denominator of x is 1.

func (*Rat)MarshalTextadded ingo1.3

func (x *Rat) MarshalText() (text []byte, errerror)

MarshalText implements theencoding.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; itmay 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, Quo panics.

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(sfmt.ScanState, chrune)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.

Example
package mainimport ("fmt""log""math/big")func main() {// 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 (*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)SetFloat64added ingo1.1

func (z *Rat) SetFloat64(ffloat64) *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.If b == 0, SetFrac panics.

func (*Rat)SetFrac64

func (z *Rat) SetFrac64(a, bint64) *Rat

SetFrac64 sets z to a/b and returns z.If b == 0, SetFrac64 panics.

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(xint64) *Rat

SetInt64 sets z to x and returns z.

func (*Rat)SetString

func (z *Rat) SetString(sstring) (*Rat,bool)

SetString sets z to the value of s and returns z and a boolean indicatingsuccess. s can be given as a (possibly signed) fraction "a/b", or as afloating-point number optionally followed by an exponent.If a fraction is provided, both the dividend and the divisor may be adecimal integer or independently use a prefix of “0b”, “0” or “0o”,or “0x” (or their upper-case variants) to denote a binary, octal, orhexadecimal integer, respectively. The divisor may not be signed.If a floating-point number is provided, it may be in decimal form oruse any of the same prefixes as above but for “0” to denote a non-decimalmantissa. A leading “0” is considered a decimal leading 0; it does notindicate octal representation in this case.An optional base-10 “e” or base-2 “p” (or their upper-case variants)exponent may be provided as well, except for hexadecimal floats whichonly accept an (optional) “p” exponent (because an “e” or “E” cannotbe distinguished from a mantissa digit). If the exponent's absolute valueis too large, the operation may fail.The entire string, not just a prefix, must be valid for success. If theoperation failed, the value of z is undefined but the returned value is nil.

Example
package mainimport ("fmt""math/big")func main() {r := new(big.Rat)r.SetString("355/113")fmt.Println(r.FloatString(3))}
Output:3.142

func (*Rat)SetUint64added ingo1.13

func (z *Rat) SetUint64(xuint64) *Rat

SetUint64 sets z to x and returns z.

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)UnmarshalTextadded ingo1.3

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

UnmarshalText implements theencoding.TextUnmarshaler interface.

typeRoundingModeadded ingo1.5

type RoundingModebyte

RoundingMode determines how aFloat value is rounded to thedesired precision. Rounding may change theFloat value; therounding error is described by theFloat'sAccuracy.

Example
package mainimport ("fmt""math/big")func main() {operands := []float64{2.6, 2.5, 2.1, -2.1, -2.5, -2.6}fmt.Print("   x")for mode := big.ToNearestEven; mode <= big.ToPositiveInf; mode++ {fmt.Printf("  %s", mode)}fmt.Println()for _, f64 := range operands {fmt.Printf("%4g", f64)for mode := big.ToNearestEven; mode <= big.ToPositiveInf; mode++ {// sample operands above require 2 bits to represent mantissa// set binary precision to 2 to round them to integer valuesf := new(big.Float).SetPrec(2).SetMode(mode).SetFloat64(f64)fmt.Printf("  %*g", len(mode.String()), f)}fmt.Println()}}
Output:   x  ToNearestEven  ToNearestAway  ToZero  AwayFromZero  ToNegativeInf  ToPositiveInf 2.6              3              3       2             3              2              3 2.5              2              3       2             3              2              3 2.1              2              2       2             3              2              3-2.1             -2             -2      -2            -3             -3             -2-2.5             -2             -3      -2            -3             -3             -2-2.6             -3             -3      -2            -3             -3             -2

const (ToNearestEvenRoundingMode =iota// == IEEE 754-2008 roundTiesToEvenToNearestAway// == IEEE 754-2008 roundTiesToAwayToZero// == IEEE 754-2008 roundTowardZeroAwayFromZero// no IEEE 754-2008 equivalentToNegativeInf// == IEEE 754-2008 roundTowardNegativeToPositiveInf// == IEEE 754-2008 roundTowardPositive)

These constants define supported rounding modes.

func (RoundingMode)Stringadded ingo1.5

func (iRoundingMode) String()string

typeWord

type Worduint

A Word represents a single digit of a multi-precision unsigned integer.

Source Files

View all Source files

Directories

PathSynopsis
internal
asmgen
Asmgen generates math/big assembly.
Asmgen generates math/big assembly.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2026 Movatter.jp