math

package module
v1.5.0 Latest Latest
Warning

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

Go to latest
Published: Jan 6, 2025 License: Apache-2.0 Imports: 13 Imported by: 7,109

Documentation

Overview

Package math implements custom Cosmos SDK math types used for arithmetic operations. Signed and unsigned integer types utilize Golang's standard library big integers types, having a maximum bit length of 256 bits.

Index

Examples

Constants

View Source
const (
	// MaxExponent is the highest exponent supported. Exponents near this range will
	// perform very slowly (many seconds per operation).
	MaxExponent = apd.MaxExponent
	// MinExponent is the lowest exponent supported with the same limitations as
	// MaxExponent.
	MinExponent = apd.MinExponent
)
View Source
const (
	// LegacyPrecision number of decimal places
	LegacyPrecision = 18

	// LegacyDecimalPrecisionBits bits required to represent the above precision
	// Ceiling[Log2[10^Precision - 1]]
	// Deprecated: This is unused and will be removed
	LegacyDecimalPrecisionBits = 60
)
View Source
const MaxBitLen = 256

MaxBitLen defines the maximum bit length supported bit Int and Uint types.

Variables

View Source
var (
	ErrInvalidDec         = errors.Register(mathCodespace, 1, "invalid decimal")
	ErrUnexpectedRounding = errors.Register(mathCodespace, 2, "unexpected rounding")
	ErrNonIntegral        = errors.Register(mathCodespace, 3, "value is non-integral")
)
View Source
var (
	// ErrIntOverflow is the error returned when an integer overflow occurs
	ErrIntOverflow = errors.New("integer overflow")
	// ErrDivideByZero is the error returned when a divide by zero occurs
	ErrDivideByZero = errors.New("divide by zero")
)

Integer errors

View Source
var (
	ErrLegacyEmptyDecimalStr      = errors.New("decimal string cannot be empty")
	ErrLegacyInvalidDecimalLength = errors.New("invalid decimal length")
	ErrLegacyInvalidDecimalStr    = errors.New("invalid decimal string")
)

Decimal errors

Functions

func FormatDec

func FormatDec(v string) (string, error)

FormatDec formats a decimal (as encoded in protobuf) into a value-rendered string following ADR-050. This function operates with string manipulation (instead of manipulating the sdk.Dec object).

func FormatInt

func FormatInt(v string) (string, error)

FormatInt formats an integer (encoded as in protobuf) into a value-rendered string following ADR-050. This function operates with string manipulation (instead of manipulating the int or math.Int object).

func IntEq

func IntEq(t *testing.T, exp, got Int) (*testing.T, bool, string, string, string)

IntEq intended to be used with require/assert: require.True(IntEq(...))

func LegacyDecApproxEq

func LegacyDecApproxEq(t *testing.T, d1, d2, tol LegacyDec) (*testing.T, bool, string, string, string)

func LegacyDecEq

func LegacyDecEq(t *testing.T, exp, got LegacyDec) (*testing.T, bool, string, string, string)

LegacyDecEq intended to be used with require/assert: require.True(DecEq(...))

func LegacyDecsEqual

func LegacyDecsEqual(d1s, d2s []LegacyDec) bool

LegacyDecsEqual return true if two decimal arrays are equal.

func LegacySortableDecBytes

func LegacySortableDecBytes(dec LegacyDec) []byte

LegacySortableDecBytes returns a byte slice representation of a Dec that can be sorted. Left and right pads with 0s so there are 18 digits to left and right of the decimal point. For this reason, there is a maximum and minimum value for this, enforced by ValidSortableDec.

func LegacyValidSortableDec

func LegacyValidSortableDec(dec LegacyDec) bool

LegacyValidSortableDec ensures that a Dec is within the sortable bounds, a Dec can't have a precision of less than 10^-18. Max sortable decimal was set to the reciprocal of SmallestDec.

func Max

func Max[T constraints.Ordered](a, b T, rest ...T) T

func Min

func Min[T constraints.Ordered](a, b T, rest ...T) T

func UintOverflow

func UintOverflow(i *big.Int) error

UintOverflow returns true if a given unsigned integer overflows and false otherwise.

Types

type Dec added in v1.5.0

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

Dec is a wrapper struct around apd.Decimal that does no mutation of apd.Decimal's when performing arithmetic, instead creating a new apd.Decimal for every operation ensuring usage is safe.

Using apd.Decimal directly can be unsafe because apd operations mutate the underlying Decimal, but when copying the big.Int structure can be shared between Decimal instances causing corruption. This was originally discovered in regen0-network/mainnet#15.

Example
d := NewDecFromInt64(1) // 1
fmt.Println(d.String())

d = NewDecWithExp(-1234, -3) // -1.234
fmt.Println(d.String())
d = NewDecWithExp(1234, 0) // 1234
fmt.Println(d.String())
d = NewDecWithExp(1234, 1) // 12340
fmt.Println(d.String())

// scientific notation
d, err := NewDecFromString("1.23E+4") // 12300
if err != nil {
	panic(err)
}
fmt.Println(d.String())

// decimal notation
d, err = NewDecFromString("1.234")
if err != nil {
	panic(err)
}
fmt.Println(d.String())
Output:

1
-1.234
1234
12340
12300
1.234

func NewDecFromInt64 added in v1.5.0

func NewDecFromInt64(x int64) Dec

NewDecFromInt64 converts an int64 to a Dec type. This function is useful for creating Dec values from integer literals or variables, ensuring they can be used in high-precision arithmetic operations defined for Dec types.

Example: - NewDecFromInt64(123) returns a Dec representing the value 123.

func NewDecFromString added in v1.5.0

func NewDecFromString(s string) (Dec, error)

NewDecFromString converts a string to a Dec type, supporting standard, scientific, and negative notations. It handles non-numeric values and overflow conditions, returning errors for invalid inputs like "NaN" or "Infinity".

Examples: - "123" -> Dec{123} - "-123.456" -> Dec{-123.456} - "1.23E4" -> Dec{12300} - "NaN" or "Infinity" -> ErrInvalidDec

The internal representation is an arbitrary-precision decimal: Negative × Coeff × 10*Exponent The maximum exponent is 100_000 and must not be exceeded. Following values would be invalid: 1E100001 -> ErrInvalidDec -1E100001 -> ErrInvalidDec 1E-100001 -> ErrInvalidDec

This function is essential for converting textual data into Dec types for numerical operations.

func NewDecWithExp added in v1.5.0

func NewDecWithExp(coeff int64, exp int32) Dec

NewDecWithExp creates a Dec from a coefficient and exponent, calculated as coeff * 10^exp. Useful for precise decimal representations. Although this method can be used with a higher than maximum exponent or lower than minimum exponent, further arithmetic or other method may fail.

Example: - NewDecWithExp(123, -2) -> Dec representing 1.23.

func (Dec) Add added in v1.5.0

func (x Dec) Add(y Dec) (Dec, error)

Add returns a new Dec representing the sum of `x` and `y` using returning a new Dec, we use apd.BaseContext. This function ensures that no arguments are mutated during the operation and checks for overflow conditions. If an overflow occurs, an error is returned.

The precision is much higher as long as the max exponent is not exceeded. If the max exponent is exceeded, an error is returned. For example: - 1e100000 + -1e-1 - 1e100000 + 9e100000 - 1e100001 + 0 We can see that in apd.BaseContext the max exponent is defined hence we cannot exceed.

This function wraps any internal errors with a context-specific error message for clarity.

Example
sum, err := NewDecFromInt64(1).Add(NewDecFromInt64(1)) // 1 + 1 = 2
if err != nil {
	panic(err)
}
fmt.Println(sum.String())

const maxExp = 100_000
_, err = NewDecWithExp(1, maxExp).Add(NewDecFromInt64(1)) // 1E+1000000 + 1
if err != nil {
	fmt.Println(err.Error())
}

sum, err = NewDecWithExp(1, maxExp).Add(NewDecWithExp(1, maxExp)) // 1E+1000000 + 1E+1000000
if err != nil {
	panic(err)
}
fmt.Println(sum.Text('E'))

// the max exponent must not be exceeded
_, err = NewDecWithExp(1, maxExp+1).Add(NewDecFromInt64(1)) // 1E+1000001 + 1
if err != nil {
	fmt.Println(err.Error())
}

const minExp = -100_000
// same for min exponent
_, err = NewDecWithExp(1, minExp-1).Add(NewDecFromInt64(1)) // 1E-1000001 + 1
if err != nil {
	fmt.Println(err.Error())
}
// not even by adding 0
_, err = NewDecWithExp(1, minExp-1).Add(NewDecFromInt64(0)) // 1E-1000001 + 0
if err != nil {
	fmt.Println(err.Error())
}
Output:

2
2E+100000
add: exponent out of range: invalid decimal
add: exponent out of range: invalid decimal
add: exponent out of range: invalid decimal

func (Dec) BigInt added in v1.5.0

func (x Dec) BigInt() (*big.Int, error)

BigInt converts x to a *big.Int or returns an error if x cannot fit precisely into an *big.Int.

func (Dec) Cmp added in v1.5.0

func (x Dec) Cmp(y Dec) int

Cmp compares x and y and returns: -1 if x < y 0 if x == y +1 if x > y undefined if d or x are NaN

func (Dec) Equal added in v1.5.0

func (x Dec) Equal(y Dec) bool

Equal checks if the decimal values of x and y are exactly equal. It returns true if both decimals represent the same value, otherwise false.

func (Dec) Int64 added in v1.5.0

func (x Dec) Int64() (int64, error)

Int64 converts x to an int64 or returns an error if x cannot fit precisely into an int64.

func (Dec) IsFinite added in v1.5.0

func (x Dec) IsFinite() bool

IsFinite returns true if the decimal is finite.

func (Dec) IsNegative added in v1.5.0

func (x Dec) IsNegative() bool

IsNegative returns true if the decimal is negative.

func (Dec) IsPositive added in v1.5.0

func (x Dec) IsPositive() bool

IsPositive returns true if the decimal is positive.

func (Dec) IsZero added in v1.5.0

func (x Dec) IsZero() bool

IsZero returns true if the decimal is zero.

func (Dec) Marshal added in v1.5.0

func (x Dec) Marshal() ([]byte, error)

Marshal serializes the decimal value into a byte slice in text format. This method represents the decimal in a portable and compact hybrid notation. Based on the exponent value, the number is formatted into decimal: -ddddd.ddddd, no exponent or scientific notation: -d.ddddE±dd

For example, the following transformations are made:

  • 0 -> 0
  • 123 -> 123
  • 10000 -> 10000
  • -0.001 -> -0.001
  • -0.000000001 -> -1E-9

Returns:

  • A byte slice of the decimal in text format.
  • An error if the decimal cannot be reduced or marshaled properly.

func (Dec) MarshalJSON added in v1.5.0

func (x Dec) MarshalJSON() ([]byte, error)

MarshalJSON serializes the Dec struct into a JSON-encoded byte slice using scientific notation.

func (Dec) MarshalTo added in v1.5.0

func (x Dec) MarshalTo(data []byte) (n int, err error)

MarshalTo encodes the receiver into the provided byte slice and returns the number of bytes written and any error encountered.

func (Dec) Modulo added in v1.5.0

func (x Dec) Modulo(y Dec) (Dec, error)

Modulo computes the remainder of division of x by y using decimal128 precision. It returns an error if y is zero or if any other error occurs during the computation.

Example:

  • 7 mod 3 = 1
  • 6 mod 3 = 0
Example
sum, err := NewDecFromInt64(7).Modulo(NewDecFromInt64(3)) // 7 mod 3 = 1
if err != nil {
	panic(err)
}
fmt.Println(sum.String())
Output:

1

func (Dec) Mul added in v1.5.0

func (x Dec) Mul(y Dec) (Dec, error)

Mul returns a new Dec with value `x*y` (formatted as decimal128, with 34 digit precision) without mutating any argument and error if there is an overflow.

Example
sum, err := NewDecFromInt64(2).Mul(NewDecFromInt64(3)) // 2 * 3
if err != nil {
	panic(err)
}
fmt.Println(sum.String())

sum, err = NewDecWithExp(125, -2).Mul(NewDecFromInt64(2)) // 1.25 * 2
if err != nil {
	panic(err)
}
fmt.Println(sum.String())

const maxExp = 100_000
sum, err = NewDecWithExp(1, maxExp).Mul(NewDecFromInt64(10)) // 1e100000 * 10 -> err
if err != nil {
	fmt.Println(err.Error())
}

sum, err = NewDecFromInt64(1).Mul(NewDecFromInt64(0)) // 1 * 0
if err != nil {
	panic(err)
}
fmt.Println(sum.String())
Output:

6
2.50
exponent out of range: invalid decimal
0

func (Dec) MulExact added in v1.5.0

func (x Dec) MulExact(y Dec) (Dec, error)

MulExact multiplies two Dec values x and y without rounding, using decimal128 precision. It returns an error if rounding is necessary to fit the result within the 34-digit limit.

Example: - MulExact(Dec{1.234}, Dec{2.345}) -> Dec{2.893}, or ErrUnexpectedRounding if precision exceeded.

Note: - This function does not alter the original Dec values.

Example
sum, err := NewDecFromInt64(2).MulExact(NewDecFromInt64(3)) // 2 * 3
if err != nil {
	panic(err)
}
fmt.Println(sum.String())

sum, err = NewDecWithExp(125, -2).MulExact(NewDecFromInt64(2)) // 1.25 * 2
if err != nil {
	panic(err)
}
fmt.Println(sum.String())

const maxExp = 100_000
sum, err = NewDecWithExp(1, maxExp).MulExact(NewDecFromInt64(10)) // 1e100000 * 10 -> err
if err != nil {
	fmt.Println(err.Error())
}
a, err := NewDecFromString("0.12345678901234567890123456789012345") // 35 digits after the comma
if err != nil {
	panic(err)
}
sum, err = a.MulExact(NewDecFromInt64(1))
if err != nil {
	fmt.Println(err.Error())
}

sum, err = a.MulExact(NewDecFromInt64(0))
if err != nil {
	panic(err)
}
fmt.Println(sum.String())

sum, err = NewDecFromInt64(1).MulExact(NewDecFromInt64(0)) // 1 * 0
if err != nil {
	panic(err)
}
fmt.Println(sum.String())
Output:

6
2.50
exponent out of range: invalid decimal
unexpected rounding
0E-35
0

func (Dec) NumDecimalPlaces added in v1.5.0

func (x Dec) NumDecimalPlaces() uint32

NumDecimalPlaces returns the number of decimal places in x.

func (Dec) Quo added in v1.5.0

func (x Dec) Quo(y Dec) (Dec, error)

Quo performs division of x by y using the decimal128 context with 34 digits of precision. It returns a new Dec or an error if the division is not feasible due to constraints of decimal128.

Within Quo half up rounding may be performed to match the defined precision. If this is unwanted, QuoExact should be used instead.

Key error scenarios: - Division by zero (e.g., `123 / 0` or `0 / 0`) results in ErrInvalidDec. - Non-representable values due to extreme ratios or precision limits.

Examples: - `0 / 123` yields `0`. - `123 / 123` yields `1.000000000000000000000000000000000`. - `-123 / 123` yields `-1.000000000000000000000000000000000`. - `4 / 9` yields `0.4444444444444444444444444444444444`. - `5 / 9` yields `0.5555555555555555555555555555555556`. - `6 / 9` yields `0.6666666666666666666666666666666667`. - `1e-100000 / 10` yields error.

This function is non-mutative and enhances error clarity with specific messages.

Example
sum, err := NewDecFromInt64(6).Quo(NewDecFromInt64(2)) // 6 / 2
if err != nil {
	panic(err)
}
fmt.Println(sum.String())

sum, err = NewDecFromInt64(7).Quo(NewDecFromInt64(2)) // 7 / 2
if err != nil {
	panic(err)
}
fmt.Println(sum.String())

sum, err = NewDecFromInt64(4).Quo(NewDecFromInt64(9)) // 4 / 9
if err != nil {
	panic(err)
}
fmt.Println(sum.String())

const minExp = -100_000
sum, err = NewDecWithExp(1, minExp).Quo(NewDecFromInt64(10)) // 1e-100000 / 10
if err != nil {
	fmt.Println(err.Error())
}

sum, err = NewDecFromInt64(1).Quo(NewDecFromInt64(0)) // 1 / 0 -> error
if err != nil {
	fmt.Println(err.Error())
}
Output:

3.000000000000000000000000000000000
3.500000000000000000000000000000000
0.4444444444444444444444444444444444
exponent out of range: invalid decimal
division by zero: invalid decimal

func (Dec) QuoExact added in v1.5.0

func (x Dec) QuoExact(y Dec) (Dec, error)

QuoExact performs division like Quo and additionally checks for rounding. It returns ErrUnexpectedRounding if any rounding occurred during the division. If the division is exact, it returns the result without error.

This function is particularly useful in financial calculations or other scenarios where precision is critical and rounding could lead to significant errors.

Key error scenarios: - Division by zero (e.g., `123 / 0` or `0 / 0`) results in ErrInvalidDec. - Rounding would have occurred, which is not permissible in this context, resulting in ErrUnexpectedRounding.

Examples: - `0 / 123` yields `0` without rounding. - `123 / 123` yields `1.000000000000000000000000000000000` exactly. - `-123 / 123` yields `-1.000000000000000000000000000000000` exactly. - `1 / 9` yields error for the precision limit - `1e-100000 / 10` yields error for crossing the lower exponent limit. - Any division resulting in a non-terminating decimal under decimal128 precision constraints triggers ErrUnexpectedRounding.

This function does not mutate any arguments and wraps any internal errors with a context-specific error message for clarity.

Example
sum, err := NewDecFromInt64(6).QuoExact(NewDecFromInt64(2)) // 6 / 2
if err != nil {
	panic(err)
}
fmt.Println(sum.String())

sum, err = NewDecFromInt64(7).QuoExact(NewDecFromInt64(2)) // 7 / 2
if err != nil {
	panic(err)
}
fmt.Println(sum.String())

sum, err = NewDecFromInt64(4).QuoExact(NewDecFromInt64(9)) // 4 / 9 -> error
if err != nil {
	fmt.Println(err.Error())
}

const minExp = -100_000
sum, err = NewDecWithExp(1, minExp).QuoExact(NewDecFromInt64(10)) // 1e-100000 / 10 -> error
if err != nil {
	fmt.Println(err.Error())
}

sum, err = NewDecFromInt64(1).QuoExact(NewDecFromInt64(0)) // 1 / 0 -> error
if err != nil {
	fmt.Println(err.Error())
}
Output:

3.000000000000000000000000000000000
3.500000000000000000000000000000000
unexpected rounding
exponent out of range: invalid decimal
division by zero: invalid decimal

func (Dec) QuoInteger added in v1.5.0

func (x Dec) QuoInteger(y Dec) (Dec, error)

QuoInteger performs integer division of x by y, returning a new Dec formatted as decimal128 with 34 digit precision. This function returns the integer part of the quotient, discarding any fractional part, and is useful in scenarios where only the whole number part of the division result is needed without rounding.

Key error scenarios: - Division by zero (e.g., `123 / 0`) results in ErrInvalidDec. - Overflow conditions if the result exceeds the storage capacity of a decimal128 formatted number.

Examples: - `123 / 50` yields `2` (since the fractional part .46 is discarded). - `100 / 3` yields `33` (since the fractional part .3333... is discarded). - `50 / 100` yields `0` (since 0.5 is less than 1 and thus discarded).

The function does not mutate any arguments and ensures that errors are wrapped with specific messages for clarity.

Example
sum, err := NewDecFromInt64(6).QuoInteger(NewDecFromInt64(2)) // 6 / 2
if err != nil {
	panic(err)
}
fmt.Println(sum.String())

sum, err = NewDecFromInt64(7).QuoInteger(NewDecFromInt64(2)) // 7 / 2
if err != nil {
	panic(err)
}
fmt.Println(sum.String())

sum, err = NewDecFromInt64(4).QuoInteger(NewDecFromInt64(9)) // 4 / 9 -> error
if err != nil {
	panic(err)
}
fmt.Println(sum.String())

const minExp = -100_000
sum, err = NewDecWithExp(1, minExp).QuoInteger(NewDecFromInt64(10)) // 1e-100000 / 10 -> 0
if err != nil {
	panic(err)
}
fmt.Println(sum.String())

sum, err = NewDecFromInt64(1).QuoInteger(NewDecFromInt64(0)) // 1 / 0 -> error
if err != nil {
	fmt.Println(err.Error())
}
Output:

3
3
0
0
division by zero: invalid decimal

func (Dec) Reduce added in v1.5.0

func (x Dec) Reduce() (Dec, int)

Reduce returns a copy of x with all trailing zeros removed and the number of zeros that were removed. It does not modify the original decimal.

func (Dec) SdkIntTrim added in v1.5.0

func (x Dec) SdkIntTrim() (Int, error)

SdkIntTrim rounds the decimal number towards zero to the nearest integer, then converts and returns it as `sdkmath.Int`. It handles both positive and negative values correctly by truncating towards zero. This function returns an ErrNonIntegral error if the resulting integer is larger than the maximum value that `sdkmath.Int` can represent.

func (Dec) Size added in v1.5.0

func (x Dec) Size() int

Size returns the number of bytes required to encode the Dec value, which is useful for determining storage requirements.

func (Dec) String added in v1.5.0

func (x Dec) String() string

String formatted in decimal notation: '-ddddd.dddd', no exponent

func (Dec) Sub added in v1.5.0

func (x Dec) Sub(y Dec) (Dec, error)

Sub returns a new Dec representing the sum of `x` and `y` using returning a new Dec, we use apd.BaseContext. This function ensures that no arguments are mutated during the operation and checks for overflow conditions. If an overflow occurs, an error is returned.

The precision is much higher as long as the max exponent is not exceeded. If the max exponent is exceeded, an error is returned. For example: - 1e-100001 - 0 - 1e100000 - 1e-1 - 1e100000 - -9e100000 - 1e100001 - 1e100001 (upper limit exceeded) - 1e-100001 - 1e-100001 (lower limit exceeded) We can see that in apd.BaseContext the max exponent is defined hence we cannot exceed.

This function wraps any internal errors with a context-specific error message for clarity.

Example
sum, err := NewDecFromInt64(2).Sub(NewDecFromInt64(1)) // 2 - 1
if err != nil {
	panic(err)
}
fmt.Println(sum.String())

const maxExp = 100_000
_, err = NewDecWithExp(1, maxExp).Sub(NewDecFromInt64(1)) // 1E+1000000 - 1
if err != nil {
	fmt.Println(err.Error())
}

sum, err = NewDecWithExp(1, maxExp).Sub(NewDecWithExp(1, maxExp)) // 1E+1000000 - 1E+1000000
if err != nil {
	panic(err)
}
fmt.Println(sum.Text('E'))

// the max exponent must not be exceeded
_, err = NewDecWithExp(1, maxExp+1).Sub(NewDecFromInt64(1)) // 1E+1000001 - 1
if err != nil {
	fmt.Println(err.Error())
}

const minExp = -100_000
// same for min exponent
_, err = NewDecWithExp(1, minExp-1).Sub(NewDecFromInt64(1)) // 1E-1000001 - 1
if err != nil {
	fmt.Println(err.Error())
}
// not even by adding 0
_, err = NewDecWithExp(1, minExp-1).Sub(NewDecFromInt64(0)) // 1E-1000001 - 0
if err != nil {
	fmt.Println(err.Error())
}
Output:

1
0E+100000
sub: exponent out of range: invalid decimal
sub: exponent out of range: invalid decimal
sub: exponent out of range: invalid decimal

func (Dec) Text added in v1.5.0

func (x Dec) Text(format byte) string

Text converts the floating-point number x to a string according to the given format. The format is one of:

'e'	-d.dddde±dd, decimal exponent, exponent digits
'E'	-d.ddddE±dd, decimal exponent, 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

If format is a different character, Text returns a "%" followed by the unrecognized.Format character. The 'f' format has the possibility of displaying precision that is not present in the Decimal when it appends zeros (the 'g' format avoids the use of 'f' in this case). All other formats always show the exact precision of the Decimal.

func (*Dec) Unmarshal added in v1.5.0

func (x *Dec) Unmarshal(data []byte) error

Unmarshal parses a byte slice containing a text-formatted decimal and stores the result in the receiver. It returns an error if the byte slice does not represent a valid decimal.

func (*Dec) UnmarshalJSON added in v1.5.0

func (x *Dec) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface for the Dec type, converting JSON strings to Dec objects.

type Int

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

Int wraps big.Int with a 256 bit range bound Checks overflow, underflow and division by zero Exists in range from -(2^256 - 1) to 2^256 - 1

func MaxInt

func MaxInt(i, i2 Int) Int

MaxInt returns the maximum between two integers.

func MinInt

func MinInt(i1, i2 Int) Int

MinInt return the minimum of the ints

func NewInt

func NewInt(n int64) Int

NewInt constructs Int from int64

func NewIntFromBigInt

func NewIntFromBigInt(i *big.Int) Int

NewIntFromBigInt constructs Int from big.Int. If the provided big.Int is nil, it returns an empty instance. This function panics if the bit length is > 256. Note, the caller can safely mutate the argument after this function returns.

func NewIntFromBigIntMut added in v1.2.0

func NewIntFromBigIntMut(i *big.Int) Int

NewIntFromBigIntMut constructs Int from big.Int. If the provided big.Int is nil, it returns an empty instance. This function panics if the bit length is > 256. Note, this function mutate the argument.

func NewIntFromString

func NewIntFromString(s string) (res Int, ok bool)

NewIntFromString constructs Int from string

func NewIntFromUint64

func NewIntFromUint64(n uint64) Int

NewIntFromUint64 constructs an Int from a uint64.

func NewIntWithDecimal

func NewIntWithDecimal(n int64, dec int) Int

NewIntWithDecimal constructs Int with decimal Result value is n*10^dec

func OneInt

func OneInt() Int

OneInt returns Int value with one

func ZeroInt

func ZeroInt() Int

ZeroInt returns Int value with zero

func (Int) Abs

func (i Int) Abs() Int

Abs returns the absolute value of Int.

func (Int) Add

func (i Int) Add(i2 Int) (res Int)

Add adds Int from another

func (Int) AddRaw

func (i Int) AddRaw(i2 int64) Int

AddRaw adds int64 to Int

func (Int) BigInt

func (i Int) BigInt() *big.Int

BigInt converts Int to big.Int

func (Int) BigIntMut added in v1.2.0

func (i Int) BigIntMut() *big.Int

BigIntMut converts Int to big.Int, mutative the input

func (Int) Equal

func (i Int) Equal(i2 Int) bool

Equal compares two Ints

func (Int) GT

func (i Int) GT(i2 Int) bool

GT returns true if first Int is greater than second

func (Int) GTE

func (i Int) GTE(i2 Int) bool

GTE returns true if receiver Int is greater than or equal to the parameter Int.

func (Int) Int64

func (i Int) Int64() int64

Int64 converts Int to int64 Panics if the value is out of range

func (Int) IsInt64

func (i Int) IsInt64() bool

IsInt64 returns true if Int64() not panics

func (Int) IsNegative

func (i Int) IsNegative() bool

IsNegative returns true if Int is negative

func (Int) IsNil

func (i Int) IsNil() bool

IsNil returns true if Int is uninitialized

func (Int) IsPositive

func (i Int) IsPositive() bool

IsPositive returns true if Int is positive

func (Int) IsUint64

func (i Int) IsUint64() bool

IsUint64 returns true if Uint64() not panics

func (Int) IsZero

func (i Int) IsZero() bool

IsZero returns true if Int is zero

func (Int) LT

func (i Int) LT(i2 Int) bool

LT returns true if first Int is lesser than second

func (Int) LTE

func (i Int) LTE(i2 Int) bool

LTE returns true if first Int is less than or equal to second

func (Int) Marshal

func (i Int) Marshal() ([]byte, error)

Marshal implements the gogo proto custom type interface.

func (Int) MarshalAmino

func (i Int) MarshalAmino() ([]byte, error)

MarshalAmino Override Amino binary serialization by proxying to protobuf.

func (Int) MarshalJSON

func (i Int) MarshalJSON() ([]byte, error)

MarshalJSON defines custom encoding scheme

func (*Int) MarshalTo

func (i *Int) MarshalTo(data []byte) (n int, err error)

MarshalTo implements the gogo proto custom type interface.

func (Int) MarshalYAML

func (i Int) MarshalYAML() (interface{}, error)

MarshalYAML returns the YAML representation.

func (Int) Mod

func (i Int) Mod(i2 Int) Int

Mod returns remainder after dividing with Int

func (Int) ModRaw

func (i Int) ModRaw(i2 int64) Int

ModRaw returns remainder after dividing with int64

func (Int) Mul

func (i Int) Mul(i2 Int) (res Int)

Mul multiples two Ints

func (Int) MulRaw

func (i Int) MulRaw(i2 int64) Int

MulRaw multiplies Int and int64

func (Int) Neg

func (i Int) Neg() (res Int)

Neg negates Int

func (Int) Quo

func (i Int) Quo(i2 Int) (res Int)

Quo divides Int with Int

func (Int) QuoRaw

func (i Int) QuoRaw(i2 int64) Int

QuoRaw divides Int with int64

func (Int) SafeAdd added in v1.3.0

func (i Int) SafeAdd(i2 Int) (res Int, err error)

SafeAdd adds Int from another and returns an error if overflow

func (Int) SafeMod added in v1.3.0

func (i Int) SafeMod(i2 Int) (res Int, err error)

SafeMod returns remainder after dividing with Int and returns an error if division by zero

func (Int) SafeMul added in v1.3.0

func (i Int) SafeMul(i2 Int) (res Int, err error)

SafeMul multiples Int from another and returns an error if overflow

func (Int) SafeQuo added in v1.3.0

func (i Int) SafeQuo(i2 Int) (res Int, err error)

SafeQuo divides Int with Int and returns an error if division by zero

func (Int) SafeSub added in v1.3.0

func (i Int) SafeSub(i2 Int) (res Int, err error)

SafeSub subtracts Int from another and returns an error if overflow or underflow

func (Int) Sign

func (i Int) Sign() int

Sign returns sign of Int

func (*Int) Size

func (i *Int) Size() int

Size implements the gogo proto custom type interface.

func (Int) String

func (i Int) String() string

String returns human-readable string

func (Int) Sub

func (i Int) Sub(i2 Int) (res Int)

Sub subtracts Int from another

func (Int) SubRaw

func (i Int) SubRaw(i2 int64) Int

SubRaw subtracts int64 from Int

func (Int) ToLegacyDec added in v1.1.0

func (i Int) ToLegacyDec() LegacyDec

ToLegacyDec converts Int to LegacyDec

func (Int) Uint64

func (i Int) Uint64() uint64

Uint64 converts Int to uint64 Panics if the value is out of range

func (*Int) Unmarshal

func (i *Int) Unmarshal(data []byte) error

Unmarshal implements the gogo proto custom type interface.

func (*Int) UnmarshalAmino

func (i *Int) UnmarshalAmino(bz []byte) error

func (*Int) UnmarshalJSON

func (i *Int) UnmarshalJSON(bz []byte) error

UnmarshalJSON defines custom decoding scheme

type LegacyDec

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

LegacyDec NOTE: never use new(Dec) or else we will panic unmarshalling into the nil embedded big.Int

var LegacyMaxSortableDec LegacyDec

LegacyMaxSortableDec is the largest Dec that can be passed into SortableDecBytes() Its negative form is the least Dec that can be passed in.

func LegacyMaxDec

func LegacyMaxDec(d1, d2 LegacyDec) LegacyDec

LegacyMaxDec maximum decimal between two

func LegacyMinDec

func LegacyMinDec(d1, d2 LegacyDec) LegacyDec

LegacyMinDec minimum decimal between two

func LegacyMustNewDecFromStr

func LegacyMustNewDecFromStr(s string) LegacyDec

LegacyMustNewDecFromStr Decimal from string, panic on error

func LegacyNewDec

func LegacyNewDec(i int64) LegacyDec

LegacyNewDec create a new Dec from integer assuming whole number

func LegacyNewDecFromBigInt

func LegacyNewDecFromBigInt(i *big.Int) LegacyDec

LegacyNewDecFromBigInt create a new Dec from big integer assuming whole numbers CONTRACT: prec <= Precision

func LegacyNewDecFromBigIntWithPrec

func LegacyNewDecFromBigIntWithPrec(i *big.Int, prec int64) LegacyDec

LegacyNewDecFromBigIntWithPrec create a new Dec from big integer assuming whole numbers CONTRACT: prec <= Precision

func LegacyNewDecFromInt

func LegacyNewDecFromInt(i Int) LegacyDec

LegacyNewDecFromInt create a new Dec from big integer assuming whole numbers CONTRACT: prec <= Precision

func LegacyNewDecFromIntWithPrec

func LegacyNewDecFromIntWithPrec(i Int, prec int64) LegacyDec

LegacyNewDecFromIntWithPrec create a new Dec from big integer with decimal place at prec CONTRACT: prec <= Precision

func LegacyNewDecFromStr

func LegacyNewDecFromStr(str string) (LegacyDec, error)

LegacyNewDecFromStr create a decimal from an input decimal string. valid must come in the form:

(-) whole integers (.) decimal integers

examples of acceptable input include:

-123.456
456.7890
345
-456789

NOTE - An error will return if more decimal places are provided in the string than the constant Precision.

CONTRACT - This function does not mutate the input str.

func LegacyNewDecWithPrec

func LegacyNewDecWithPrec(i, prec int64) LegacyDec

LegacyNewDecWithPrec create a new Dec from integer with decimal place at prec CONTRACT: prec <= Precision

func LegacyOneDec

func LegacyOneDec() LegacyDec

func LegacySmallestDec

func LegacySmallestDec() LegacyDec

func LegacyZeroDec

func LegacyZeroDec() LegacyDec

func (LegacyDec) Abs

func (d LegacyDec) Abs() LegacyDec

func (LegacyDec) AbsMut added in v1.0.1

func (d LegacyDec) AbsMut() LegacyDec

func (LegacyDec) Add

func (d LegacyDec) Add(d2 LegacyDec) LegacyDec

Add addition

func (LegacyDec) AddMut

func (d LegacyDec) AddMut(d2 LegacyDec) LegacyDec

AddMut mutable addition

func (LegacyDec) ApproxRoot

func (d LegacyDec) ApproxRoot(root uint64) (guess LegacyDec, err error)

ApproxRoot returns an approximate estimation of a Dec's positive real nth root using Newton's method (where n is positive). The algorithm starts with some guess and computes the sequence of improved guesses until an answer converges to an approximate answer. It returns `|d|.ApproxRoot() * -1` if input is negative. A maximum number of 100 iterations is used a backup boundary condition for cases where the answer never converges enough to satisfy the main condition.

func (LegacyDec) ApproxSqrt

func (d LegacyDec) ApproxSqrt() (LegacyDec, error)

ApproxSqrt is a wrapper around ApproxRoot for the common special case of finding the square root of a number. It returns -(sqrt(abs(d)) if input is negative.

func (LegacyDec) BigInt

func (d LegacyDec) BigInt() *big.Int

BigInt returns a copy of the underlying big.Int.

func (LegacyDec) BigIntMut added in v1.3.0

func (d LegacyDec) BigIntMut() *big.Int

BigIntMut converts LegacyDec to big.Int, mutative the input

func (LegacyDec) Ceil

func (d LegacyDec) Ceil() LegacyDec

Ceil returns the smallest integer value (as a decimal) that is greater than or equal to the given decimal.

func (LegacyDec) Clone

func (d LegacyDec) Clone() LegacyDec

func (LegacyDec) Equal

func (d LegacyDec) Equal(d2 LegacyDec) bool

func (LegacyDec) Float64

func (d LegacyDec) Float64() (float64, error)

Float64 returns the float64 representation of a Dec. Will return the error if the conversion failed.

func (LegacyDec) Format

func (d LegacyDec) Format(s fmt.State, verb rune)

Format format decimal state

func (LegacyDec) GT

func (d LegacyDec) GT(d2 LegacyDec) bool

func (LegacyDec) GTE

func (d LegacyDec) GTE(d2 LegacyDec) bool

func (LegacyDec) ImmutOp

func (d LegacyDec) ImmutOp(op func(LegacyDec, LegacyDec) LegacyDec, d2 LegacyDec) LegacyDec

func (LegacyDec) ImmutOpInt

func (d LegacyDec) ImmutOpInt(op func(LegacyDec, Int) LegacyDec, d2 Int) LegacyDec

func (LegacyDec) ImmutOpInt64

func (d LegacyDec) ImmutOpInt64(op func(LegacyDec, int64) LegacyDec, d2 int64) LegacyDec

func (LegacyDec) IsInValidRange added in v1.4.0

func (d LegacyDec) IsInValidRange() bool

IsInValidRange returns true when the value is between the upper limit of (2^256 * 10^18) and the lower limit of -1*(2^256 * 10^18).

func (LegacyDec) IsInteger

func (d LegacyDec) IsInteger() bool

IsInteger is integer, e.g. decimals are zero

func (LegacyDec) IsNegative

func (d LegacyDec) IsNegative() bool

func (LegacyDec) IsNil

func (d LegacyDec) IsNil() bool

func (LegacyDec) IsPositive

func (d LegacyDec) IsPositive() bool

func (LegacyDec) IsZero

func (d LegacyDec) IsZero() bool

func (LegacyDec) LT

func (d LegacyDec) LT(d2 LegacyDec) bool

func (LegacyDec) LTE

func (d LegacyDec) LTE(d2 LegacyDec) bool

func (LegacyDec) Marshal

func (d LegacyDec) Marshal() ([]byte, error)

Marshal implements the gogo proto custom type interface.

func (LegacyDec) MarshalAmino

func (d LegacyDec) MarshalAmino() ([]byte, error)

MarshalAmino Override Amino binary serialization by proxying to protobuf.

func (LegacyDec) MarshalJSON

func (d LegacyDec) MarshalJSON() ([]byte, error)

MarshalJSON marshals the decimal

func (*LegacyDec) MarshalTo

func (d *LegacyDec) MarshalTo(data []byte) (n int, err error)

MarshalTo implements the gogo proto custom type interface.

func (LegacyDec) MarshalYAML

func (d LegacyDec) MarshalYAML() (interface{}, error)

MarshalYAML returns the YAML representation.

func (LegacyDec) Mul

func (d LegacyDec) Mul(d2 LegacyDec) LegacyDec

Mul multiplication

func (LegacyDec) MulInt

func (d LegacyDec) MulInt(i Int) LegacyDec

MulInt multiplication

func (LegacyDec) MulInt64

func (d LegacyDec) MulInt64(i int64) LegacyDec

MulInt64 multiplication with int64

func (LegacyDec) MulInt64Mut

func (d LegacyDec) MulInt64Mut(i int64) LegacyDec

func (LegacyDec) MulIntMut

func (d LegacyDec) MulIntMut(i Int) LegacyDec

func (LegacyDec) MulMut

func (d LegacyDec) MulMut(d2 LegacyDec) LegacyDec

MulMut mutable multiplication

func (LegacyDec) MulRoundUp added in v1.1.0

func (d LegacyDec) MulRoundUp(d2 LegacyDec) LegacyDec

MulRoundUp multiplication round up at precision end.

func (LegacyDec) MulRoundUpMut added in v1.1.0

func (d LegacyDec) MulRoundUpMut(d2 LegacyDec) LegacyDec

MulRoundUpMut mutable multiplication with round up at precision end.

func (LegacyDec) MulTruncate

func (d LegacyDec) MulTruncate(d2 LegacyDec) LegacyDec

MulTruncate multiplication truncate

func (LegacyDec) MulTruncateMut

func (d LegacyDec) MulTruncateMut(d2 LegacyDec) LegacyDec

MulTruncateMut mutable multiplication truncate

func (LegacyDec) MustFloat64

func (d LegacyDec) MustFloat64() float64

MustFloat64 returns the float64 representation of a Dec. Would panic if the conversion failed.

func (LegacyDec) Neg

func (d LegacyDec) Neg() LegacyDec

func (LegacyDec) NegMut

func (d LegacyDec) NegMut() LegacyDec

func (LegacyDec) Power

func (d LegacyDec) Power(power uint64) LegacyDec

Power returns the result of raising to a positive integer power

func (LegacyDec) PowerMut

func (d LegacyDec) PowerMut(power uint64) LegacyDec

func (LegacyDec) Quo

func (d LegacyDec) Quo(d2 LegacyDec) LegacyDec

Quo quotient

func (LegacyDec) QuoInt

func (d LegacyDec) QuoInt(i Int) LegacyDec

QuoInt quotient

func (LegacyDec) QuoInt64

func (d LegacyDec) QuoInt64(i int64) LegacyDec

QuoInt64 quotient with int64

func (LegacyDec) QuoInt64Mut

func (d LegacyDec) QuoInt64Mut(i int64) LegacyDec

func (LegacyDec) QuoIntMut

func (d LegacyDec) QuoIntMut(i Int) LegacyDec

func (LegacyDec) QuoMut

func (d LegacyDec) QuoMut(d2 LegacyDec) LegacyDec

QuoMut mutable quotient

func (LegacyDec) QuoRoundUp

func (d LegacyDec) QuoRoundUp(d2 LegacyDec) LegacyDec

QuoRoundUp quotient, round up

func (LegacyDec) QuoRoundupMut

func (d LegacyDec) QuoRoundupMut(d2 LegacyDec) LegacyDec

QuoRoundupMut mutable quotient, round up

func (LegacyDec) QuoTruncate

func (d LegacyDec) QuoTruncate(d2 LegacyDec) LegacyDec

QuoTruncate quotient truncate

func (LegacyDec) QuoTruncateMut

func (d LegacyDec) QuoTruncateMut(d2 LegacyDec) LegacyDec

QuoTruncateMut divides the current LegacyDec value by the provided LegacyDec value, truncating the result.

func (LegacyDec) RoundInt

func (d LegacyDec) RoundInt() Int

RoundInt round the decimal using bankers rounding

func (LegacyDec) RoundInt64

func (d LegacyDec) RoundInt64() int64

RoundInt64 rounds the decimal using bankers rounding

func (LegacyDec) Set

func (d LegacyDec) Set(d2 LegacyDec) LegacyDec

func (LegacyDec) SetInt64

func (d LegacyDec) SetInt64(i int64) LegacyDec

func (*LegacyDec) Size

func (d *LegacyDec) Size() int

Size implements the gogo proto custom type interface.

func (LegacyDec) String

func (d LegacyDec) String() string

func (LegacyDec) Sub

func (d LegacyDec) Sub(d2 LegacyDec) LegacyDec

Sub subtraction

func (LegacyDec) SubMut

func (d LegacyDec) SubMut(d2 LegacyDec) LegacyDec

SubMut mutable subtraction

func (LegacyDec) TruncateDec

func (d LegacyDec) TruncateDec() LegacyDec

TruncateDec truncates the decimals from the number and returns a Dec

func (LegacyDec) TruncateInt

func (d LegacyDec) TruncateInt() Int

TruncateInt truncates the decimals from the number and returns an Int

func (LegacyDec) TruncateInt64

func (d LegacyDec) TruncateInt64() int64

TruncateInt64 truncates the decimals from the number and returns an int64

func (*LegacyDec) Unmarshal

func (d *LegacyDec) Unmarshal(data []byte) error

Unmarshal implements the gogo proto custom type interface.

func (*LegacyDec) UnmarshalAmino

func (d *LegacyDec) UnmarshalAmino(bz []byte) error

func (*LegacyDec) UnmarshalJSON

func (d *LegacyDec) UnmarshalJSON(bz []byte) error

UnmarshalJSON defines custom decoding scheme

type Uint

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

Uint wraps integer with 256 bit range bound Checks overflow, underflow and division by zero Exists in range from 0 to 2^256-1

func MaxUint

func MaxUint(u1, u2 Uint) Uint

MaxUint returns the maximum of the Uints

func MinUint

func MinUint(u1, u2 Uint) Uint

MinUint returns the minimum of the Uints

func NewUint

func NewUint(n uint64) Uint

NewUint constructs Uint from uint64

func NewUintFromBigInt

func NewUintFromBigInt(i *big.Int) Uint

NewUintFromBigInt constructs Uint from big.Int Panics if i is negative or wider than 256 bits

func NewUintFromString

func NewUintFromString(s string) Uint

NewUintFromString constructs Uint from string Panics if parsed s is negative or wider than 256 bits

func OneUint

func OneUint() Uint

OneUint returns Uint value with one.

func ParseUint

func ParseUint(s string) (Uint, error)

ParseUint reads a string-encoded Uint value and return a Uint.

func RelativePow

func RelativePow(x, n, b Uint) (z Uint)

RelativePow raises x to the power of n, where x (and the result, z) are scaled by factor b for example, RelativePow(210, 2, 100) = 441 (2.1^2 = 4.41)

func ZeroUint

func ZeroUint() Uint

ZeroUint returns unsigned zero.

func (Uint) Add

func (u Uint) Add(u2 Uint) Uint

Add adds Uint from another

func (Uint) AddUint64

func (u Uint) AddUint64(u2 uint64) Uint

AddUint64 convert uint64 and add it to Uint

func (Uint) BigInt

func (u Uint) BigInt() *big.Int

BigInt converts Uint to big.Int

func (Uint) BigIntMut added in v1.2.0

func (u Uint) BigIntMut() *big.Int

BigIntMut converts Uint to big.Int, mutative the input

func (Uint) Decr

func (u Uint) Decr() Uint

Decr decrements the Uint by one. Decr will panic if the Uint is zero.

func (Uint) Equal

func (u Uint) Equal(u2 Uint) bool

Equal compares two Uints

func (Uint) GT

func (u Uint) GT(u2 Uint) bool

GT returns true if first Uint is greater than second

func (Uint) GTE

func (u Uint) GTE(u2 Uint) bool

GTE returns true if first Uint is greater than second

func (Uint) Incr

func (u Uint) Incr() Uint

Incr increments the Uint by one.

func (Uint) IsNil

func (u Uint) IsNil() bool

IsNil returns true if Uint is uninitialized

func (Uint) IsZero

func (u Uint) IsZero() bool

IsZero returns 1 if the uint equals to 0.

func (Uint) LT

func (u Uint) LT(u2 Uint) bool

LT returns true if first Uint is lesser than second

func (Uint) LTE

func (u Uint) LTE(u2 Uint) bool

LTE returns true if first Uint is lesser than or equal to the second

func (Uint) Marshal

func (u Uint) Marshal() ([]byte, error)

Marshal implements the gogo proto custom type interface.

func (Uint) MarshalAmino

func (u Uint) MarshalAmino() ([]byte, error)

MarshalAmino override Amino binary serialization by proxying to protobuf.

func (Uint) MarshalJSON

func (u Uint) MarshalJSON() ([]byte, error)

MarshalJSON defines custom encoding scheme

func (*Uint) MarshalTo

func (u *Uint) MarshalTo(data []byte) (n int, err error)

MarshalTo implements the gogo proto custom type interface.

func (Uint) Mod

func (u Uint) Mod(u2 Uint) Uint

Mod returns remainder after dividing with Uint Panics if u2 is zero

func (Uint) Mul

func (u Uint) Mul(u2 Uint) (res Uint)

Mul multiplies two Uints

func (Uint) MulUint64

func (u Uint) MulUint64(u2 uint64) (res Uint)

MulUint64 multiplies two Uints

func (Uint) Quo

func (u Uint) Quo(u2 Uint) (res Uint)

Quo divides Uint with Uint

func (Uint) QuoUint64

func (u Uint) QuoUint64(u2 uint64) Uint

QuoUint64 divides Uint with uint64

func (*Uint) Size

func (u *Uint) Size() int

Size implements the gogo proto custom type interface.

func (Uint) String

func (u Uint) String() string

String returns human-readable string

func (Uint) Sub

func (u Uint) Sub(u2 Uint) Uint

Sub adds Uint from another

func (Uint) SubUint64

func (u Uint) SubUint64(u2 uint64) Uint

SubUint64 adds Uint from another

func (Uint) Uint64

func (u Uint) Uint64() uint64

Uint64 converts Uint to uint64 Panics if the value is out of range

func (*Uint) Unmarshal

func (u *Uint) Unmarshal(data []byte) error

Unmarshal implements the gogo proto custom type interface.

func (*Uint) UnmarshalAmino

func (u *Uint) UnmarshalAmino(bz []byte) error

func (*Uint) UnmarshalJSON

func (u *Uint) UnmarshalJSON(bz []byte) error

UnmarshalJSON defines custom decoding scheme

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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