decimal

package module
Version: v0.0.2 Latest Latest
Warning

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

Go to latest
Published: May 30, 2020 License: BSD-2-Clause Imports: 11 Imported by: 0

README

decimal

godocb travisb coverb goreportb

Package decimal implements arbitrary-precision decimal floating-point arithmetic for Go.

Rationale

How computers represent numbers internally is of no import for most applications. However numerical applications that interract with humans must use the same number base as humans. A very simple example is this: https://play.golang.org/p/CVjiDCdhyoR where 1.1 + 0.11 = 1.2100000000000002. Not quite what one would expect.

There are other arbitrary-precision decimal floating-point libraries available, but most use a binray representation of the mantissa (building on top of big.Int), use external C libraries or are just plain slow.

This started out as an experiment on how an implementation using a pure decimal representation would fare performance-wise. Secondary goals were to implement it with an API that would match the Go standard library's math/big API (for better or worse), and build it in such a way that it could some day be integrated into the Go standard library.

Admittedly, this actually started out while doing some yak shaving, combined with an NIH syndrom, but the result was well worth it.

Features

The implementation is in essence a port of big.Float to decimal floating-point, and the API is identical to that of *big.Float with the exception of a few additional getters and setters, an FMA operation, and helper functions to support implementation of missing low-level Decimal functionality outside this package.

Unlike big.Float, the mantissa of a Decimal is stored in a little-endian Word slice as "declets" of 9 or 19 decimal digits per 32 or 64 bits Word. All arithmetic operations are performed directly in base 10**9 or 10**19 without conversion to/from binary (see Performance below for a more in-depth discussion of this choice).

While basic operations are slower than with a binary representation, some operations like rounding (happening after every other operation!), or aligning mantissae (in add/subtract) are much cheaper.

Decimal and IEEE-754

The decimal package supports IEEE-754 rounding modes, signed zeros, infinity, and an exactly rounded Sqrt. Other functions like Log will be implemented in a future "math" sub-package. All results are rounded to the desired precision (no manual rounding).

NaN values are not directly supported (like in big.Float). They can be seen as "signaling NaNs" in IEEE-754 terminology, that is when a NaN is generated as a result of an operation, it causes a panic. Applications that need to handle NaNs gracefully can use Go's built-in panic/recover machanism to handle these efficiently: NaNs cause a panic with an ErrNaN which can be tested to distinguish NaNs from other causes of panic.

On the other hand, the context sub-package provides Contexts, which allow panic-free operation and a form of quiet-NaNs whereby any NaN generated by an operation will make the context enter into an error state. Further operations with the context will be no-ops until (*Context).Err is called to check for errors.

Mantissae are always normalized, as a result, Decimals have a single possible representation:

0.1 <= mantissa < 1; d = mantissa × 10**exponent

so there is no notion of scale and no Quantize operation.

TODO's and upcoming features

  • Some math primitives are implemented in assembler. Right now only the amd64 version is implemented, so we're still missing i386, arm, mips, power, riscV, and s390. The amd64 version could also use a good review (my assembly days date back to the Motorola MC68000). HELP WANTED!
  • Complete decimal conversion tests
  • A math sub-package that will provide at least the functions required by IEEE-754
  • Some performance improvement ideas:
    • try a non-normalized mantissa.
    • in add, there are some cycles to shave off by combining the shift and add for simple cases (initial testing yielded mitigated results. Wait and see)

The decimal API is frozen, that is, any additional features will be added in sub-packages.

Well, with the exception of NewDecimal: The current integer mantissa × 10**exp, works well enough, but I'm not truly happy with it. Early versions were using a float64 value as initializer, but that lead to unexpected side effects where one would expect the number to be exact; not quite so as it turned out, so it's not an option either.

Performance

There are other full-featured arbitrary-precision decimal-floating point libraries for Go out there, like Eric Lagergren's decimal, CockroachDB's apd, or Shopspring's decimal.

For users only interested in performance here are the benchmark results of this package versus the others using Eric's Pi test (times are in ns/op sorted from fastest to slowest at 38 digits of precision):

digits 9 19 38 100 500 5000
Eric's decimal (Go) 6415 30254 65171 194263 1731528 89841923
decimal 12887 42720 100878 348865 4212811 342349031
Eric's decimal (GDA) 7124 39357 107720 392453 5421146 1175936547
Shopspring's decimal 39528 96261 204017 561321 3402562 97370022
apd 70833 301098 1262021 9859180 716558666 ???

Note that Eric's decimal uses a separate logic for decimals < 1e19 (mantissa stored in a single uint64), which explains its impressive perfomance for low precisions.

In additions and subtractions the operands' mantissae need to be aligned (shifted), this results in an additional multiplication by 10**shift. In implementations that use a binary representation of the matissa, this is faster for shifts < 19, but performance degrades as shifts get higher. With a decimal representation, this requires a multiplication as well but always by a single Word, regardless of precision.

Rounding happens after every operation in decimal and Eric's decimal in GDA mode (not in Go mode, which explains its speed). Rounding requires a decimal shift right, which translates to a division by 10**shift. Again for small shifts, binary representations are faster, but degrades even faster as precision gets higher. On decimal implementations, this operation is quite fast since it translates to a memcpy and a divmod of the least significant Word.

This explains why decimal's performace degrades slower than Eric's decimal-GDA as precision increases, and why Eric's decimal in Go mode is so fast (no rounding, which surprisingly counter-balances the high cost of mantissae alignment).

Caveats

The Float <-> Decimal conversion code needs some love.

The math/big API is designed to keep memory allocations to a minimum, but some people find it cumbersome. Indeed it requires some practice to get used to it, so here's a quick rundown of what to do and not do:

Most APIs look like:

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

where the function sets the receiver z to the result of a + b and returns 'z'. The fact that the function returns the receiver is meant to allow chaining of operations:

s := new(Decimal).Mul(new(Decimal).Mul(r, r), pi) // d = r**2 * pi

If we don't care about what happens to r, we can just:

s := new(Decimal).Mul(r.Mul(r, r), pi)            // r *= r; d = r * pi

and save one memory allocation.

However, NEVER assign the result to a variable:

d := new(Decimal).SetUint(4)
d2 := d.Mul(d, d) // d2 == 16, but d == 16 as well!

Again, the sole intent behind returning the receiver is chaining of operations. By assigning it to a variable, you will shoot yourself in the foot and kill puppies in some far away land, so never assign the result of an operation!

However, feel free do do this:

d.Mul(d, d) // d = d*d

The code will properly detect that the receiver is also one of the arguments (possibly both), and allocate temporary storage space if (and only if) necessary. Should this kind of construct fail, please file an issue.

License

Simplified BSD license. See the LICENSE file.

The decimal package reuses a lot of code from the Go standard library, governed by a 3-Clause BSD license. See the LICENSE-go file.

I'm aware that software using this package might have to include both licenses, which might be a hassle; tracking licenses from dependencies is hard enough as it is. I'd love to have a single license and hand over copyright to "The Go authors", but the clause restricting use of the names of contributors for endorsement of a derived work in the 3-Clause BSD license that Go uses is problematic. i.e. I can't just use it as-is, mentioning Google Inc., as that would be an infringement in itself (well, that's the way I see it, but IANAL). On the other hand, any piece of software written in Go should include the Go license anyway...

Any helpful insights are welcome.

Documentation

Overview

Package decimal implements arbitrary-precision decimal floating-point arithmetic.

The implementation is heavily based on big.Float and the API is identical to that of *big.Float with the exception of a few additional getters and setters, an FMA operation, and helper functions to support implementation of missing low-level Decimal functionality outside this package (see the math sub-package).

Howvever, and unlike big.Float, the mantissa of a decimal is stored in a little-endian Word slice as "declets" of 9 or 19 decimal digits per 32 or 64 bits Word. All arithmetic operations are performed directly in base 10**9 or 10**19 without conversion to/from binary.

The mantissa of a Decimal is always normalized, that is the most significant digit of the mantissa is always a non-zero digit and:

0.1 <= mantissa < 1                       (1)

The bounds for a finite Dicimal x are:

0.1 × 10**MinExp <= x < 1 × 10**MaxExp    (2)

As a consequence to points (1) and (2), and unlike in the IEEE-754 standard, a finite Decimal can only be a normal number (no subnormal numbers) and there is no Quantize operation.

The zero value for a Decimal corresponds to 0. Thus, new values can be declared in the usual ways and denote 0 without further initialization:

x := new(Decimal)  // x is a *Decimal of value 0

Alternatively, new Decimal values can be allocated and initialized with the function:

func NewDecimal(x int64, exp int) *Decimal

NewDecimal(x, exp) returns a *Decimal set to the value of x×10**exp. More flexibility is provided with explicit setters, for instance:

z := new(Decimal).SetUint64(123)    // z3 := 123.0

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

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

For unary and binary operations, the result is the receiver (usually named z in that case; see below); if it is one of the operands x or y it may be safely overwritten (and its memory reused).

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

c.Add(a, b)

computes the sum a + b and stores the result in c, overwriting whatever value was held in c before. Unless specified otherwise, operations permit aliasing 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 be much better controlled. Instead of having to allocate new memory for each result, 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 operands are usually named x, y, a, b, and so on, but never z. A parameter specifying the result is named z (typically the receiver).

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

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

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

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

func (x *Decimal) Sign() int

Various methods support conversions between strings and corresponding numeric values, and vice versa: Decimal implements the Stringer interface for a (default) string representation of the value, but also provides SetString methods to initialize a Decimal value from a string in a variety of supported formats (see the SetString documentation).

Finally, *Decimal satisfies the fmt package's Scanner interface for scanning and the Formatter interface for formatted printing.

Index

Constants

View Source
const (
	DigitsPerWord = _DW // number of decimal digits per 32 or 64 bits mantissa Word
	DecimalBase   = _DB // decimal base
)
View Source
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.

View Source
const DefaultDecimalPrec = 34

DefaultDecimalPrec is the default minimum precision used when creating a new Decimal from a *big.Int, *big.Rat, uint64, int64, or string. An uint64 requires up to 20 digits, which amounts to 2 x 19-digits Words (64 bits) or 3 x 9-digits Words (32 bits). Forcing the precision to 20 digits would result in 18 or 7 unused digits. Using 34 instead gives a higher precision at no performance or memory cost on 64 bits platforms (but one more Word on 32 bits) and gives room for 2 to 4 extra digits of extra precision for internal computations at no added performance or memory cost. Also 34 digits matches the precision of IEEE-754 decimal128.

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

This section is empty.

Types

type Accuracy

type Accuracy int8

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

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

Constants describing the Accuracy of a Decimal.

func (Accuracy) String

func (i Accuracy) String() string

type Decimal

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

A nonzero finite Decimal represents a multi-precision decimal floating point number

sign × mantissa × 10**exponent

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

Each Decimal value also has a precision, rounding mode, and accuracy. The precision is the maximum number of mantissa decimal digits 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 *Decimal 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 Decimals 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 16 or 34 and using matching rounding mode (typically ToNearestEven), Decimal operations produce the same results as the corresponding decimal64 or decimal128 IEEE-754 decimal arithmetic for operands that correspond to normal (i.e., not subnormal) decimal64 or decimal128 numbers. Exponent underflow and overflow lead to a 0 or an Infinity for different values than IEEE-754 because Decimal exponents have a much larger range.

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

Operations always take pointer arguments (*Decimal) rather than Decimal values, and each unique Decimal value requires its own unique *Decimal pointer. To "copy" a Decimal value, an existing (or newly allocated) Decimal must be set to a new value using the Decimal.Set method; shallow copies of Decimals are not supported and may lead to errors.

func NewDecimal

func NewDecimal(x int64, exp int) *Decimal

NewDecimal allocates and returns a new Decimal set to x×10**exp, with precision DefaultDecimalPrec and rounding mode ToNearestEven.

The result will be set to ±0 if x < 0.1×10**MinPexp, or ±Inf if x >= 1×10**MaxExp.

func ParseDecimal

func ParseDecimal(s string, base int, prec uint, mode RoundingMode) (d *Decimal, b int, err error)

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

func (*Decimal) Abs

func (z *Decimal) Abs(x *Decimal) *Decimal

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

func (*Decimal) Acc

func (x *Decimal) Acc() Accuracy

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

func (*Decimal) Add

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

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.

func (*Decimal) Append

func (x *Decimal) Append(buf []byte, fmt byte, prec int) []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 (*Decimal) BitsExp

func (x *Decimal) BitsExp() ([]Word, int32)

BitsExp provides raw (unchecked but fast) access to x by returning its mantissa (as a little-endian Word slice) and exponent. The result and x share the same underlying array.

Should the returned slice nned to be extended, check its capacity first:

if newSize <= cap(mant) {
	mant = mant[:newSize] // reuse mant
}

Bits is intended to support implementation of missing low-level Decimal functionality outside this package; it should be avoided otherwise.

func (*Decimal) Cmp

func (x *Decimal) Cmp(y *Decimal) 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

func (*Decimal) Copy

func (z *Decimal) Copy(x *Decimal) *Decimal

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 (*Decimal) FMA

func (z *Decimal) FMA(x, y, u *Decimal) *Decimal

FMA sets z to x * y + u, computed with only one rounding. (That is, FMA performs the fused multiply-add of x, y, and u.) If z's precision is 0, it is changed to the larger of x's, y's, or u's precision before the operation. Rounding, and accuracy reporting are as for Add. FMA panics with ErrNaN if multiplying zero with an infinity, or if adding two infinities with opposite signs. The value of z is undefined in that case.

func (*Decimal) Float

func (x *Decimal) Float(z *big.Float) *big.Float

Float sets z to the (possibly rounded) value of x. If a non-nil *big.Float argument z is provided, Float stores the result in z instead of allocating a new big.Float. If z's precision is 0, it is changed to max(⌈x.Prec() * log2(10)⌉, 64).

func (*Decimal) Float32

func (x *Decimal) 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 (*Decimal) Float64

func (x *Decimal) 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 (*Decimal) Format

func (x *Decimal) Format(s fmt.State, format rune)

Format implements fmt.Formatter. It accepts the regular formats for floating-point numbers 'e', 'E', 'f', 'F', 'g', and 'G', as well as 'b', 'p' and 'v'. See (*Decimal).Text for the interpretation of 'b' and 'p'. The 'v' format is handled like 'g'. Format also supports specification of the minimum precision in 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 package for details.

func (*Decimal) GobDecode

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

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

func (*Decimal) GobEncode

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

GobEncode implements the gob.GobEncoder interface. The Decimal value and all its attributes (precision, rounding mode, accuracy) are marshaled.

func (*Decimal) Int

func (x *Decimal) Int(z *big.Int) (*big.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 (*Decimal) Int64

func (x *Decimal) 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 (*Decimal) IsInf

func (x *Decimal) IsInf() bool

IsInf reports whether x is +Inf or -Inf.

func (*Decimal) IsInt

func (x *Decimal) IsInt() bool

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

func (*Decimal) IsZero

func (x *Decimal) IsZero() bool

IsZero reports whether x is +0 or -0.

func (*Decimal) MantExp

func (x *Decimal) MantExp(mant *Decimal) (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 × 10**exp, with 0.1 <= |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 (*Decimal) MarshalText

func (x *Decimal) MarshalText() (text []byte, err error)

MarshalText implements the encoding.TextMarshaler interface. Only the Decimal value is marshaled (in full precision), other attributes such as precision or accuracy are ignored.

func (*Decimal) MinPrec

func (x *Decimal) 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 (*Decimal) Mode

func (x *Decimal) Mode() RoundingMode

Mode returns the rounding mode of x.

func (*Decimal) Mul

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

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 (*Decimal) Neg

func (z *Decimal) Neg(x *Decimal) *Decimal

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

func (*Decimal) Parse

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

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

For base 0, an underscore character “_” may appear between a base prefix and an adjacent digit, and between successive digits; such underscores do not change the value of the number, or the returned digit count. Incorrect placement of underscores is reported as an error if there are no other errors. If base != 0, underscores are not recognized and thus terminate scanning like any other character that 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 fit all digits of the mantissa 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 base argument 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 and no 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 then base 10) exponent; for instance, "0x1.fffffffffffffp1023" (using base 0) represents the maximum float64 value. For hexadecimal mantissae, the exponent character must be one of 'p' or 'P', if present (an "e" or "E" exponent indicator cannot be distinguished from a mantissa digit).

Note that rounding only happens if z's precision is not zero and less than the number of digits in the mantissa or with a base 2 exponent, in which case it is best to use ParseFloat then z.SetFloat.

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

func (*Decimal) Prec

func (x *Decimal) Prec() uint

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

func (*Decimal) Quo

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

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

func (x *Decimal) Rat(z *big.Rat) (*big.Rat, Accuracy)

Rat returns the rational number corresponding to x; or nil if x is an infinity. The result is Exact if 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 (*Decimal) Scan

func (z *Decimal) 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 formats whose verbs are supported by fmt.Scan for floating point values, which are: 'b' (binary), 'e', 'E', 'f', 'F', 'g' and 'G'. Scan doesn't handle ±Inf.

func (*Decimal) Set

func (z *Decimal) Set(x *Decimal) *Decimal

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 (*Decimal) SetBitsExp

func (z *Decimal) SetBitsExp(mant []Word, exp int64) *Decimal

SetBitsExp provides raw (checked, yet fast) access to z by setting it to a positive number with mantissa mant (interpreted as a little-endian Word slice) and exponent exp, returning z rounded to z.Prec(). The result and mant share the same underlying array. If mant is not normalized, SetBitsExp will normalize it and adjust the exponent accordingly.

A mantissa is normalized when its most significant Word has a non-zero most significant digit:

mant[len(mant)-1] / 10**(DigitsPerWord-1) != 0

The mant argument must either be a newly created Word slice or obtained as a result of a call to BitsExp with the same receiver.

SetBitsExp is intended to support implementation of missing low-level Decimal functionality outside this package; it should be avoided otherwise.

func (*Decimal) SetFloat

func (z *Decimal) SetFloat(x *big.Float) *Decimal

SetFloat sets z to the (possibly rounded) value of x and returns z. If z's precision is 0, it is changed to ⌈x.Prec() * Log10(2)⌉.

Conversion is performed using z's precision and rounding mode. Caveat: as a result this may lead to inconsistencies between the ouputs of x.Text and z.Text. To preserve this property, the conversion should be done using x's precision and rounding mode set to ToNearestEven:

p, m := z.Prec(), z.Mode()
z.SetPrec(0).SetMode(ToNearestEven).SetFloat(x)
z.SetMode(m).SetPrec(p)

func (*Decimal) SetFloat64

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

SetFloat64 sets z to the (possibly rounded) value of x and returns z. If z's precision is 0, it is changed to 17. SetFloat64 panics with ErrNaN if x is a NaN. Conversion is performed using z's precision and rounding mode. See caveat in (*Decimal).SetFloat.

func (*Decimal) SetInf

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

SetInf sets z to the infinite Decimal -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 (*Decimal) SetInt

func (z *Decimal) SetInt(x *big.Int) *Decimal

SetInt sets z to the (possibly rounded) value of x and returns z. If z's precision is 0, it is changed, after conversion, to max(z.MinPrec(), DefaultDecimalPrec) (and rounding will have no effect).

For example:

new(Decimal).SetInt(big.NewInt(1e40)).Prec() == 1

func (*Decimal) SetInt64

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

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

func (*Decimal) SetMantExp

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

SetMantExp sets z to mant × 10**exp 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.1 <= |mant| < 1.0. Specifically:

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

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 (*Decimal) SetMode

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

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 (*Decimal) SetPrec

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

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 digits 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 (*Decimal) SetRat

func (z *Decimal) SetRat(x *big.Rat) *Decimal

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 DefaultDecimalPrec; with x = a/b.

func (*Decimal) SetString

func (z *Decimal) SetString(s string) (*Decimal, 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 Parse, with base argument 0. The entire string (not just a prefix) must be valid for success. If the operation failed, the value of z is undefined but the returned value is nil.

func (*Decimal) SetUint64

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

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

func (*Decimal) Sign

func (x *Decimal) Sign() int

Sign returns:

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

func (*Decimal) Signbit

func (x *Decimal) Signbit() bool

Signbit reports whether x is negative or negative zero.

func (*Decimal) Sqrt

func (z *Decimal) Sqrt(x *Decimal) *Decimal

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

If z's precision is 0, it is changed to x's precision before the operation. Rounding is performed according to z's precision and rounding mode.

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

func (*Decimal) String

func (x *Decimal) String() string

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

func (*Decimal) Sub

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

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 (*Decimal) Text

func (x *Decimal) Text(format byte, prec int) string

Text converts the decimal 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
'p' -0.dddde±dd, decimal mantissa, decimal exponent (non-standard)
'b' -dddddde±dd, decimal mantissa, decimal exponent (non-standard)

For non-standard formats, the mantissa is printed in normalized form:

'p' decimal mantissa in [0.1, 1), or 0
'b' decimal integer mantissa using x.Prec() digits, or 0

Note that the 'b' and 'p' formats differ from big.Float: an hexadecimal representation does not make sense for decimals. These formats use a full decimal representaion instead.

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

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 decimal digits necessary to identify the value x uniquely using x.Prec() mantissa digits. The prec value is ignored for the 'b' and 'p' formats.

func (*Decimal) Uint64

func (x *Decimal) 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.

func (*Decimal) UnmarshalText

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

UnmarshalText implements the encoding.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 takes effect.

type ErrNaN

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

An ErrNaN panic is raised by a Decimal 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 RoundingMode

type RoundingMode byte

RoundingMode determines how a Decimal value is rounded to the desired precision. Rounding may change the Decimal value; the rounding error is described by the Decimal'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
)

These constants define supported rounding modes.

func (RoundingMode) String

func (i RoundingMode) String() string

type Word

type Word uint

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

Directories

Path Synopsis
Package context provides IEEE-754 style contexts for Decimals.
Package context provides IEEE-754 style contexts for Decimals.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL