Documentation ¶
Overview ¶
Package decimal provides a high-performance, arbitrary precision, floating-point decimal library.
Overview ¶
This package provides floating-point decimal numbers, useful for financial programming or calculations where a larger, more accurate representation of a number is required.
In addition to basic arithmetic operations (addition, subtraction, multiplication, and division) this package offers various mathematical functions, including the exponential function, various logarithms, and the ability to compute continued fractions.
While lean, this package is full of features. It implements interfaces like “fmt.Formatter” and intuitively utilizes verbs and flags as described in the “fmt” package. (Also included: “fmt.Scanner”, “fmt.Stringer”, “encoding.TextUnmarshaler”, and “encoding.TextMarshaler”.)
It allows users to specific explicit contexts for arithmetic operations, but doesn't require it. It provides access to NaN payloads and is more lenient when parsing a decimal from a string than the GDA specification requires.
API interfaces have been changed slightly to work more seamlessly with existing Go programs. For example, many “Quantize” implementations require a decimal as both the receiver and argument which isn't very user friendly. Instead, this library accepts a simple “int” which can be derived from an existing decimal if required.
It contains two modes of operation designed to make transitioning to various GDA "quirks" (like always rounding lossless operations) easier.
GDA: strictly adhere to the GDA specification (default) Go: utilize Go idioms, more flexibility
Goals ¶
There are three primary goals of this library:
- Correctness
By adhering to the General Decimal Arithmetic specification, this package has a well-defined structure for its arithmetic operations.
- Performance
Decimal libraries are inherently slow; this library works diligently to minimize memory allocations and utilize efficient algorithms. Performance regularly benchmarks as fast or faster than many other popular decimal libraries.
- Ease of use
Libraries should be intuitive and work out of the box without having to configure too many settings; however, precise settings should still be available.
Usage ¶
The following type is supported:
Big decimal numbers
The zero value for a Big corresponds with 0, meaning all the following are valid:
var x Big y := new(Big) z := &Big{}
Method naming is the same as math/big's, meaning:
func (z *T) SetV(v V) *T // z = v func (z *T) Unary(x *T) *T // z = unary x func (z *T) Binary(x, y *T) *T // z = x binary y func (x *T) Pred() P // p = pred(x)
In general, its conventions mirror math/big's. It is suggested to read the math/big package comments to gain an understanding of this package's conventions.
Arguments to Binary and Unary methods are allowed to alias, so the following is valid:
x := New(1, 0) x.Add(x, x) // x == 2 y := New(1, 0) y.FMA(y, x, y) // y == 3
Unless otherwise specified, the only argument that will be modified is the result (“z”). This means the following is valid and race-free:
x := New(1, 0) var g1, g2 Big go func() { g1.Add(x, x) }() go func() { g2.Add(x, x) }()
But this is not:
x := New(1, 0) var g Big go func() { g.Add(x, x) }() // BAD! RACE CONDITION! go func() { g.Add(x, x) }() // BAD! RACE CONDITION!
Index ¶
- Constants
- Variables
- func Raw(x *Big) (*uint64, *big.Int)
- type Big
- func (z *Big) Abs(x *Big) *Big
- func (z *Big) Add(x, y *Big) *Big
- func (z *Big) CeilN(n int) *Big
- func (z *Big) CheckNaNs(x, y *Big) bool
- func (x *Big) Class() string
- func (x *Big) Cmp(y *Big) int
- func (x *Big) CmpAbs(y *Big) int
- func (z *Big) Copy(x *Big) *Big
- func (z *Big) CopySign(x, y *Big) *Big
- func (z *Big) FMA(x, y, u *Big) *Big
- func (x *Big) Float(z *big.Float) *big.Float
- func (x *Big) Float64() (f float64, ok bool)
- func (z *Big) FloorN(n int) *Big
- func (x *Big) Format(s fmt.State, c rune)
- func (x *Big) Int(z *big.Int) *big.Int
- func (x *Big) Int64() (int64, bool)
- func (x *Big) IsFinite() bool
- func (x *Big) IsInf(sign int) bool
- func (x *Big) IsInt() bool
- func (x *Big) IsNaN(quiet int) bool
- func (x *Big) IsNormal() bool
- func (x *Big) IsSubnormal() bool
- func (x *Big) MarshalText() ([]byte, error)
- func (z *Big) Mul(x, y *Big) *Big
- func (z *Big) Neg(x *Big) *Big
- func (x *Big) Payload() Payload
- func (x *Big) Precision() int
- func (z *Big) Quantize(n int) *Big
- func (z *Big) Quo(x, y *Big) *Big
- func (z *Big) QuoInt(x, y *Big) *Big
- func (z *Big) QuoRem(x, y, r *Big) (*Big, *Big)
- func (x *Big) Rat(z *big.Rat) *big.Rat
- func (z *Big) Reduce() *Big
- func (z *Big) Rem(x, y *Big) *Big
- func (z *Big) Round(n int) *Big
- func (z *Big) RoundToInt() *Big
- func (x *Big) Scale() int
- func (d *Big) Scan(value interface{}) error
- func (z *Big) Set(x *Big) *Big
- func (z *Big) SetBigMantScale(value *big.Int, scale int) *Big
- func (z *Big) SetFloat(x *big.Float) *Big
- func (z *Big) SetFloat64(x float64) *Big
- func (z *Big) SetInf(signbit bool) *Big
- func (z *Big) SetMantScale(value int64, scale int) *Big
- func (z *Big) SetNaN(signal bool) *Big
- func (z *Big) SetRat(x *big.Rat) *Big
- func (z *Big) SetScale(scale int) *Big
- func (z *Big) SetString(s string) (*Big, bool)
- func (z *Big) SetUint64(x uint64) *Big
- func (x *Big) Sign() int
- func (x *Big) Signbit() bool
- func (x *Big) String() string
- func (z *Big) Sub(x, y *Big) *Big
- func (x *Big) Uint64() (uint64, bool)
- func (z *Big) UnmarshalJSON(data []byte) error
- func (z *Big) UnmarshalText(data []byte) error
- func (x *Big) Value() (driver.Value, error)
- type Condition
- type Context
- func (c Context) Add(z, x, y *Big) *Big
- func (c Context) Err() error
- func (c Context) FMA(z, x, y, u *Big) *Big
- func (c Context) Mul(z, x, y *Big) *Big
- func (c Context) Quantize(z *Big, n int) *Big
- func (c Context) Quo(z, x, y *Big) *Big
- func (c Context) QuoInt(z, x, y *Big) *Big
- func (c Context) QuoRem(z, x, y, r *Big) (*Big, *Big)
- func (c Context) Reduce(z *Big) *Big
- func (c Context) Rem(z, x, y *Big) *Big
- func (c Context) Round(z *Big) *Big
- func (c Context) RoundToInt(z *Big) *Big
- func (c Context) Set(z, x *Big) *Big
- func (c Context) SetString(z *Big, s string) (*Big, bool)
- func (c Context) Sub(z, x, y *Big) *Big
- type ErrNaN
- type OperatingMode
- type Payload
- type RoundingMode
Constants ¶
const ( MaxScale = c.MaxScale // largest allowed scale. MinScale = -MaxScale // smallest allowed scale. MaxPrecision = MaxScale // largest allowed Context precision. MinPrecision = 1 // smallest allowed Context precision. UnlimitedPrecision = MaxPrecision + 1 // no precision, but may error. DefaultPrecision = 32 // default precision for literals. )
Precision and scale limits.
Variables ¶
var ( // Context32 is the IEEE 754R Decimal32 format. Context32 = Context{ Precision: 7, RoundingMode: ToNearestEven, OperatingMode: GDA, Traps: ^(Inexact | Rounded | Subnormal), MaxScale: 96, MinScale: -95, } // Context64 is the IEEE 754R Decimal64 format. Context64 = Context{ Precision: 16, RoundingMode: ToNearestEven, OperatingMode: GDA, Traps: ^(Inexact | Rounded | Subnormal), MaxScale: 384, MinScale: -383, } // Context128 is the IEEE 754R Decimal128 format. Context128 = Context{ Precision: 34, RoundingMode: ToNearestEven, OperatingMode: GDA, Traps: ^(Inexact | Rounded | Subnormal), MaxScale: 6144, MinScale: -6143, } // ContextUnlimited provides unlimited precision decimals. ContextUnlimited = Context{ Precision: UnlimitedPrecision, RoundingMode: ToNearestEven, OperatingMode: GDA, Traps: ^(Inexact | Rounded | Subnormal), MaxScale: MaxScale, MinScale: MinScale, } )
The following Contexts are based on IEEE 754R. Each Context's RoundingMode is ToNearestEven, OperatingMode is GDA, and traps are set to every exception other than Inexact, Rounded, and Subnormal.
var Regexp = regexp.MustCompile(`(?i)(([+-]?(\d+\.\d*|\.?\d+)([eE][+-]?\d+)?)|(inf(infinity)?))|([+-]?([sq]?nan\d*))`)
Regexp matches any valid string representing a decimal that can be passed to SetString.
Functions ¶
func Raw ¶
Raw directly returns x's raw compact and unscaled values. Caveat emptor: Neither are guaranteed to be valid. Raw is intended to support missing functionality outside this package and generally should be avoided. Additionally, Raw is the only part of this package's API which is not guaranteed to remain stable. This means the function could change or disappear at any time, even across minor version numbers.
Types ¶
type Big ¶
type Big struct { // Context is the decimal's unique contextual object. Context Context // contains filtered or unexported fields }
Big is a floating-point, arbitrary-precision decimal.
It is represented as a number and a scale. If the scale is >= 0, it indicates the number of decimal digits after the radix. Otherwise, the number is multiplied by 10 to the power of the negation of the scale. More formally,
Big = number × 10**-scale
with MinScale <= scale <= MaxScale. A Big may also be ±0, ±Infinity, or ±NaN (either quiet or signaling). Non-NaN Big values are ordered, defined as the result of x.Cmp(y).
Additionally, each Big value has a contextual object which governs arithmetic operations.
func New ¶
New creates a new Big decimal with the given value and scale. For example:
New(1234, 3) // 1.234 New(42, 0) // 42 New(4321, 5) // 0.04321 New(-1, 0) // -1 New(3, -10) // 30 000 000 000
func WithContext ¶
WithContext is shorthand to create a Big decimal from a Context.
func WithPrecision ¶
WithPrecision is shorthand to create a Big decimal with a given precision.
func (*Big) CheckNaNs ¶
CheckNaNs checks if either x or y is NaN. If so, it follows the rules of NaN handling set forth in the GDA specification. The second argument, y, may be nil. It returns true if either condition is a NaN.
func (*Big) Class ¶
Class returns the “class” of x, which is one of the following:
sNaN NaN -Infinity -Normal -Subnormal -Zero +Zero +Subnormal +Normal +Infinity
func (*Big) Cmp ¶
Cmp compares x and y and returns:
-1 if x < y 0 if x == y +1 if x > y
It does not modify x or y. The result is undefined if either x or y are NaN. For an abstract comparison with NaN values, see misc.CmpTotal.
func (*Big) CmpAbs ¶
CmpAbs compares |x| and |y| and returns:
-1 if |x| < |y| 0 if |x| == |y| +1 if |x| > |y|
It does not modify x or y. The result is undefined if either x or y are NaN. For an abstract comparison with NaN values, see misc.CmpTotalAbs.
func (*Big) CopySign ¶
CopySign sets z to x with the sign of y and returns z. It accepts NaN values.
func (*Big) Float ¶
Float sets z to x and returns z. z is allowed to be nil. The result is undefined if z is a NaN value.
func (*Big) Float64 ¶
Float64 returns x as a float64 and a bool indicating whether x can fit into a float64 without truncation, overflow, or underflow. Special values are considered exact; however, special values that occur because the magnitude of x is too large to be represented as a float64 are not.
func (*Big) Format ¶
Format implements the fmt.Formatter interface. The following verbs are supported:
%s: -dddd.dd or -d.dddd±edd, depending on x %d: same as %s %v: same as %s %e: -d.dddd±edd %E: -d.dddd±Edd %f: -dddd.dd %g: same as %f
While width is honored in the same manner as the fmt package (the minimum width of the formatted number), precision is the number of significant digits in the decimal number. Given %f, however, precision is the number of digits following the radix.
Format honors all flags (such as '+' and ' ') in the same manner as the fmt package, except for '#'. Unless used in conjunction with %v, %q, or %p, the '#' flag will be ignored; decimals have no defined hexadeximal or octal representation.
%+v, %#v, %T, %#p, and %p all honor the formats specified in the fmt package's documentation.
func (*Big) Int ¶
Int sets z to x, truncating the fractional portion (if any) and returns z. z is allowed to be nil. If x is an infinity or a NaN value the result is undefined.
func (*Big) Int64 ¶
Int64 returns x as an int64, truncating towards zero. The returned boolean indicates whether the conversion to an int64 was successful.
func (*Big) IsInf ¶
IsInf returns true if x is an infinity according to sign. If sign > 0, IsInf reports whether x is positive infinity. If sign < 0, IsInf reports whether x is negative infinity. If sign == 0, IsInf reports whether x is either infinity.
func (*Big) IsInt ¶
IsInt reports whether x is an integer. Infinity and NaN values are not integers.
func (*Big) IsNaN ¶
IsNaN returns true if x is NaN. If sign > 0, IsNaN reports whether x is quiet NaN. If sign < 0, IsNaN reports whether x is signaling NaN. If sign == 0, IsNaN reports whether x is either NaN.
func (*Big) IsSubnormal ¶
IsSubnormal returns true if x is subnormal.
func (*Big) MarshalText ¶
MarshalText implements encoding.TextMarshaler.
func (*Big) Neg ¶
Neg sets z to -x and returns z. If x is positive infinity, z will be set to negative infinity and visa versa. If x == 0, z will be set to zero as well. NaN will result in an error.
func (*Big) Payload ¶
Payload returns the payload of x, provided x is a NaN value. If x is not a NaN value, the result is undefined.
func (*Big) Precision ¶
Precision returns the precision of x. That is, it returns the number of digits in the unscaled form of x. x == 0 has a precision of 1. The result is undefined if x is not finite.
func (*Big) Quantize ¶
Quantize sets z to the number equal in value and sign to z with the scale, n.
Other decimal libraries may refer to Quantize as Truncate.
func (*Big) QuoInt ¶
QuoInt sets z to x / y with the remainder truncated. See QuoRem for more details.
func (*Big) QuoRem ¶
QuoRem sets z to the quotient x / y and r to the remainder x % y, such that x = z * y + r, and returns the pair (z, r).
func (*Big) Rat ¶
Rat sets z to x and returns z. z is allowed to be nil. The result is undefined if x is an infinity or NaN value.
func (*Big) Round ¶
Round rounds z down to n digits of precision and returns z. The result is undefined if z is not finite. No rounding will occur if n <= 0. The result of Round will always be within the interval [⌊10**x⌋, z] where x = the precision of z.
func (*Big) RoundToInt ¶
RoundToInt rounds z down to an integral value.
func (*Big) Set ¶
Set sets z to x and returns z. The result might be rounded depending on z's Context, and even if z == x.
func (*Big) SetBigMantScale ¶
SetBigMantScale sets z to the given value and scale.
func (*Big) SetInf ¶
SetInf sets z to -Inf if signbit is set or +Inf is signbit is not set, and returns z.
func (*Big) SetMantScale ¶
SetMantScale sets z to the given value and scale.
func (*Big) SetNaN ¶
SetNaN sets z to a signaling NaN if signal is true or quiet NaN otherwise and returns z. No conditions are raised.
func (*Big) SetString ¶
SetString sets z to the value of s, returning z and a bool indicating success. s must be a string in one of the following formats:
1.234 1234 1.234e+5 1.234E-5 0.000001234 Inf NaN qNaN sNaN
Each value may be preceded by an optional sign, “-” or “+”. “Inf” and “NaN” map to “+Inf” and “qNaN”, respectively. NaN values may have optional diagnostic information, represented as trailing digits; for example, “NaN123”. These digits are otherwise ignored but are included for robustness.
func (*Big) Sign ¶
Sign returns:
-1 if x < 0 0 if x == 0 +1 if x > 0
No distinction is made between +0 and -0. The result is undefined if x is a NaN value.
func (*Big) Signbit ¶
Signbit reports whether x is negative, negative zero, negative infinity, or negative NaN.
func (*Big) String ¶
String returns the string representation of x. It's equivalent to the %s verb discussed in the Format method's documentation. Special cases depend on the OperatingMode.
func (*Big) Uint64 ¶
Uint64 returns x as a uint64, truncating towards zero. The returned boolean indicates whether the conversion to a uint64 was successful.
func (*Big) UnmarshalJSON ¶
UnmarshalJSON implements json.Unmarshaler.
func (*Big) UnmarshalText ¶
UnmarshalText implements encoding.TextUnmarshaler.
type Condition ¶
type Condition uint32
Condition is a bitmask value raised after or during specific operations. For example, dividing by zero is undefined so a DivisionByZero Condition flag will be set in the decimal's Context.
const ( // Clamped occurs if the scale has been modified to fit the constraints of // the decimal representation. Clamped Condition = 1 << iota // ConversionSyntax occurs when a string is converted to a decimal and does // not have a valid syntax. ConversionSyntax // DivisionByZero occurs when division is attempted with a finite, // non-zero dividend and a divisor with a value of zero. DivisionByZero // DivisionImpossible occurs when the result of integer division would // contain too many digits (i.e. be longer than the specified precision). DivisionImpossible // DivisionUndefined occurs when division is attempted with in which both // the divided and divisor are zero. DivisionUndefined // Inexact occurs when the result of an operation (e.g. division) is not // exact, or when the Overflow/Underflow Conditions occur. Inexact // InsufficientStorage occurs when the system doesn't have enough storage // (i.e. memory) to store the decimal. InsufficientStorage // InvalidContext occurs when an invalid context was detected during an // operation. This might occur if, for example, an invalid RoundingMode was // passed to a Context. InvalidContext // InvalidOperation occurs when: // // - an operand to an operation is a signaling NaN // - an attempt is made to add or subtract infinities of opposite signs // - an attempt is made to multiply zero by an infinity of either sign // - an attempt is made to divide an infinity by an infinity // - the divisor for a remainder operation is zero // - the dividend for a remainder operation is an infinity // - either operand of the quantize operation is an infinity, or the result // of a quantize operation would require greater precision than is // available // - the operand of the ln or the log10 operation is less than zero // - the operand of the square-root operation has a sign of 1 and a // non-zero coefficient // - both operands of the power operation are zero, or if the left-hand // operand is less than zero and the right-hand operand does not have an // integral value or is an infinity // InvalidOperation // Overflow occurs when the adjusted scale, after rounding, would be // greater than MaxScale. (Inexact and Rounded will also be raised.) Overflow // Rounded occurs when the result of an operation is rounded, or if an // Overflow/Underflow occurs. Rounded // Subnormal ocurs when the result of a conversion or operation is subnormal // (i.e. the adjusted scale is less than MinScale before any rounding). Subnormal // Underflow occurs when the result is inexact and the adjusted scale would // be smaller (more negative) than MinScale. Underflow )
type Context ¶
type Context struct { // MaxScale overrides the MaxScale constant so long as it's in the range // (0, MaxScale]. MaxScale int // MinScale overrides the MaxScale constant so long as it's in the range // [MinScale, 0). MinScale int // Precision is the Context's precision; that is, the maximum number of // significant digits that may result from any arithmetic operation. // Excluding any package-defined constants (e.g., “UnlimitedPrecision”), // if precision is not in the range [1, MaxPrecision] operations might // result in an error. A precision of 0 will be interpreted as // DefaultPrecision. For example, // // precision == 4 // 4 // precision == -4 // error // precision == 0 // DefaultPrecision // precision == 12 // 12 // Precision int // Traps are a set of exceptional conditions that should result in an error. Traps Condition // Conditions are a set of the most recent exceptional conditions to occur // during an operation. Conditions Condition // RoundingMode determines how a decimal is rounded. RoundingMode RoundingMode // OperatingMode which dictates how the decimal operates under certain // conditions. See OperatingMode for more information. OperatingMode OperatingMode }
Context is a per-decimal contextual object that governs specific operations.
func (Context) Quantize ¶
Quantize sets z to the number equal in value and sign to z with the scale, n.
In order to perform truncation, set the Context's RoundingMode to ToZero.
func (Context) QuoInt ¶
QuoInt sets z to x / y with the remainder truncated. See QuoRem for more details.
func (Context) QuoRem ¶
QuoRem sets z to the quotient x / y and r to the remainder x % y, such that x = z * y + r, and returns the pair (z, r).
func (Context) Round ¶
Round rounds z down to the Context's precision and returns z. The result is undefined if z is not finite. The result of Round will always be within the interval [⌊10**x⌋, z] where x = the precision of z.
func (Context) RoundToInt ¶
RoundToInt rounds z down to an integral value.
type ErrNaN ¶
type ErrNaN struct{ Msg string }
An ErrNaN is used when a decimal operation would lead to a NaN under IEEE-754 rules. An ErrNaN implements the error interface.
type OperatingMode ¶
type OperatingMode uint8
OperatingMode dictates how the decimal approaches specific non-numeric operations like conversions to strings and panicking on NaNs.
const ( // GDA strictly adheres to the General Decimal Arithmetic Specification // Version 1.70. In particular: // // - at does not panic // - all arithmetic operations will be rounded down to the proper precision // if necessary // - it utilizes traps to set both Context.Err and Context.Conditions // - its string forms of qNaN, sNaN, +Inf, and -Inf are "NaN", "sNaN", // "Infinity", and "-Infinity", respectively // GDA OperatingMode = iota // Go adheres to typical Go idioms. In particular: // // - it panics on NaN values // - has lossless (i.e., without rounding) addition, subtraction, and // multiplication // - traps are ignored; it does not set Context.Err or Context.Conditions // - its string forms of qNaN, sNaN, +Inf, and -Inf are "NaN", "NaN", // "+Inf", and "-Inf", respectively // Go )
func (OperatingMode) String ¶
func (i OperatingMode) String() string
type RoundingMode ¶
type RoundingMode uint8
RoundingMode determines how a decimal will be rounded.
const ( ToNearestEven RoundingMode = iota // == IEEE 754-2008 roundTiesToEven ToNearestAway // == IEEE 754-2008 roundTiesToAway ToZero // == IEEE 754-2008 roundTowardZero AwayFromZero // no IEEE 754-2008 equivalent ToNegativeInf // == IEEE 754-2008 roundTowardNegative ToPositiveInf // == IEEE 754-2008 roundTowardPositive )
The following rounding modes are supported.
func (RoundingMode) String ¶
func (i RoundingMode) String() string
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
internal
|
|
arith
Package arith provides performance-sensitive arithmetic operations.
|
Package arith provides performance-sensitive arithmetic operations. |
c
Package c provides internal constants.
|
Package c provides internal constants. |
Package math implements various useful mathematical functions and constants.
|
Package math implements various useful mathematical functions and constants. |
Package misc contains miscellaneous decimal routes.
|
Package misc contains miscellaneous decimal routes. |
Package suite provides a simple API for parsing and using IBM Labs' "Floating-Point Test-Suite for IEEE" This package is deprecated and will be removed in the next major version.
|
Package suite provides a simple API for parsing and using IBM Labs' "Floating-Point Test-Suite for IEEE" This package is deprecated and will be removed in the next major version. |