number

package module
v0.0.0-...-b636ac8 Latest Latest
Warning

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

Go to latest
Published: Mar 5, 2025 License: BSD-2-Clause Imports: 7 Imported by: 0

README

Number

Go Reference

Package number is a from scratch implementation of arbitrary-precision decimal floating point numbers and associated arithmetic.

Currently the only supported type is Real, which represents a real (ℝ) number. Eventually complex (ℂ) and rational (ℚ) numbers will be supported.

Arithmetic operations do not modify their operands and return values are always deep copies of underlying data. This simplifies programming patterns, but causes additional memory usage. Additionally, return values of operations will have the precision of the operand with the largest precision and the rounding mode of the receiver operand.

Example

package main

import (
	"fmt"

	"github.com/djfritz/number"
)

func main() {
	x := number.NewInt64(5)
	y, _ := number.ParseReal("-1.234e-2", number.DefaultPrecision)

	z := x.Add(y)                         // x and y are unmodified
	zln := z.Ln().Sub(number.NewInt64(2)) // it's possible to chain operations

	fmt.Printf("x       = %v\n", x)   // the %v verb prints the number in the most natural way, depending on the number
	fmt.Printf("y       = %.9f\n", y) // precision with the %f verb works as expected
	fmt.Printf("z       = %e\n", z)   // as does scientific notation
	fmt.Printf("ln(z)-2 = %v\n", zln)
}

Results in:

x       = 5
y       = -0.01234
z       = 4.98766e0
ln(z)-2 = -0.393033138098075529994326559359829

Real numbers

A zero value for a Real represents the number 0, and new values can be used in this way:

x := new(Real) // 0

Real currently supports three rounding modes:

  • Round to nearest even (the default and the default for IEEE-754 floating point numbers)
  • Round to nearest
  • Round to zero (truncate)

The default precision is 34, which is equivalent to IEEE-754-2008 128-bit decimal floating point numbers.

Tests

Beyond the unit tests in this package, Real is tested against Mike Cowlishaw's excellent dectest tests. Those tests are kept in another package, mostly to avoid embedding an ICU license in this package.

Currently, 8761 of the subset dectest tests are run against Real. Six of those currently fail, but only because of inexact rounding expected in the test suite. Real computes to better than .5ulp in those cases and provides a more accurate answer.

Documentation

Overview

Package number implements arbitrary-precision decimal floating point numbers and associated arithmetic.

Currently the only supported type is `Real`, which represents a real (ℝ) number. Eventually complex (ℂ) and rational (ℚ) numbers will be supported.

Arithmetic operations do not modify their operands and return values are always deep copies of underlying data. This simplifies programming patterns, but causes additional memory usage. Additionally, return values of operations will have the precision of the operand with the largest precision and the rounding mode of the receiver operand.

A zero value for a Real represents the number 0, and new values can be used in this way:

``` x := new(Real) // 0 ```

Real currently supports three rounding modes:

- Round to nearest even (the default and the default for IEEE-754 floating point numbers) - Round to nearest - Round to zero (truncate)

The default precision is 34, which is equivalent to IEEE-754-2008 128-bit decimal floating point numbers.

Index

Constants

View Source
const (
	FormReal = iota // A finite real number
	FormNaN         // Not a number
	FormInf         // Infinity
)

Number forms

View Source
const (
	ModeNearestEven = iota
	ModeNearest
	ModeZero
)

Rounding modes.

View Source
const DefaultPrecision = 34

The default precision for a real number. Expressed in decimal digits. 34 digits is equivalent IEEE-754-2008 128-bit decimal floating point.

View Source
const MaxExpIterations = 1000

MaxExpIterations is the maximum number of iterations in the Taylor series approximation of eˣ. If this limit is reached, Exp() will panic.

View Source
const MaxTrigIterations = 1000

MaxTrigIterations is the maximum number of iterations in the Taylor series approximation of trigonometric functions. If this limit is reached, the function will panic.

Variables

View Source
var (
	ErrInvalidCharacter = errors.New("invalid character")
)
View Source
var ErrInvalidMode = errors.New("invalid mode")

Functions

This section is empty.

Types

type Real

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

A real number. Internally stored as a real number in decimal scientific notation.

func NewFloat64

func NewFloat64(x float64) *Real

Return a new real number set to the given float64, with the default rounding mode and precision.

func NewInt64

func NewInt64(x int64) *Real

Return a new real number set to the given signed int64, with the default rounding mode and precision.

func NewUint64

func NewUint64(x uint64) *Real

Return a new real number set to the given unsigned uint64, with the default rounding mode and precision.

func ParseReal

func ParseReal(s string, p uint) (*Real, error)

ParseReal converts a string s to a Real with the given precision p.

Input beyond the given precision is ignored but not considered an error.

Input can be as a fixed precision number or in scientific notation, using a lower case 'e' for the exponent.

func (*Real) Abs

func (x *Real) Abs() *Real

Return the absolute value of x.

func (*Real) Add

func (x *Real) Add(y *Real) *Real

Return the sum of x and y.

func (*Real) Ceiling

func (x *Real) Ceiling() *Real

Returns the ceiling of x.

func (*Real) Compare

func (x *Real) Compare(y *Real) int

Compare x with y, returing an integer representing:

1  : x > y
0  : x == y
-1 : x < y

func (*Real) Copy

func (x *Real) Copy() *Real

Copy returns a deep copy of x.

func (*Real) CopyValue

func (x *Real) CopyValue(y *Real)

Copy just the value of y into x, leaving x's precision and mode the same. The result will round if needed.

func (*Real) Cos

func (x *Real) Cos() *Real

Return the cosine of x, where x is in radians.

func (*Real) Div

func (x *Real) Div(y *Real) *Real

Return the quotient of x/y.

func (*Real) Exp

func (x *Real) Exp() *Real

Return the exponential of x (eˣ).

func (*Real) Factorial

func (x *Real) Factorial() *Real

Factorial returns the integer factorial of x. If x is not an integer, the integer portion of x is used.

func (*Real) Float64

func (x *Real) Float64() (float64, error)

Return a float64 representation of the number, if possible. If not possible, err will be non-nil.

func (*Real) Floor

func (x *Real) Floor() *Real

Returns the floor of x.

func (*Real) Format

func (x *Real) Format(s fmt.State, verb rune)

Format implements fmt.Formatter. It acccepts 'd', 'e', 'f', and 'v' verbs. The 'd' verb will return an integer with trailing zeros. 'e' is the same as String(), and returns the value in scientific notation. 'f' returns a floating point value, and accepts precision modifiers. 'v' will choose an appropriate form based on the magnitude of the number.

func (*Real) GobDecode

func (x *Real) GobDecode(b []byte) error

GobDecode implements the encoding/gob.GobDecoder interface.

func (*Real) GobEncode

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

GobEncode implements the encoding/gob.GobEncoder interface.

func (*Real) Int64

func (x *Real) Int64() (int64, error)

Return an int64 representation of the number, if possible. If not possible, err will be non-nil.

func (*Real) Integer

func (x *Real) Integer() *Real

Return the integer part of a real number by truncating.

func (*Real) IsInf

func (x *Real) IsInf() bool

Returns true if x is ±Inf.

func (*Real) IsInteger

func (x *Real) IsInteger() bool

Returns true if x is an integer.

func (*Real) IsNaN

func (x *Real) IsNaN() bool

Returns true if x is NaN.

func (*Real) IsZero

func (x *Real) IsZero() bool

Returns true if x == 0.

func (*Real) Ln

func (x *Real) Ln() *Real

Return the natural logarithm (logₑ) of x.

func (*Real) Max

func (x *Real) Max(y *Real) *Real

Return a copy of the larger of x and y, or x if the values are equal.

func (*Real) Min

func (x *Real) Min(y *Real) *Real

Return a copy of the smaller of x and y, or x if the values are equal.

func (*Real) Mod

func (x *Real) Mod(y *Real) *Real

Return the modulus x%y. If either x or y are not integers, they will be truncated before the operation.

func (*Real) Mode

func (x *Real) Mode() int

Return the rounding mode.

func (*Real) Mul

func (x *Real) Mul(y *Real) *Real

Return the product of x and y.

func (*Real) Pow

func (x *Real) Pow(y *Real) *Real

Return the power of y and base x (x^y).

func (*Real) Precision

func (x *Real) Precision() uint

Returns the assigned precision of the number.

func (*Real) Reciprocal

func (x *Real) Reciprocal() *Real

Return the reciprocal of x.

func (*Real) Remainder

func (x *Real) Remainder(y *Real) *Real

Return the remainder of x/y.

func (*Real) RoundedInteger

func (x *Real) RoundedInteger() *Real

Return the rounded integer part of a real number.

func (*Real) SetFloat64

func (x *Real) SetFloat64(y float64)

Set a real number to the given float64. Rounding mode and precision are left unchanged. If precision is lower than the given value, rounding occurs.

func (*Real) SetInt64

func (x *Real) SetInt64(y int64)

Set a real number to the given signed int64. Rounding mode and precision are left unchanged. If precision is lower than the given value, rounding occurs.

func (*Real) SetMode

func (x *Real) SetMode(m int) error

Set the rounding mode.

func (*Real) SetPrecision

func (x *Real) SetPrecision(y uint)

Set the precision of the given number and round if necessary.

func (*Real) SetUint64

func (x *Real) SetUint64(y uint64)

Set a real number to the given unsigned uint64. Rounding mode and precision are left unchanged. If precision is lower than the given value, rounding occurs.

func (*Real) Sin

func (x *Real) Sin() *Real

Return the sine of x, where x is in radians.

func (*Real) Sqrt

func (x *Real) Sqrt() *Real

Return the square root of x.

func (*Real) String

func (x *Real) String() string

Return the string form of the real number in scientific notation.

func (*Real) Sub

func (x *Real) Sub(y *Real) *Real

Return the subtraction of y from x.

func (*Real) Tan

func (x *Real) Tan() *Real

Return the tangent of x, where x is in radians.

func (*Real) Uint64

func (x *Real) Uint64() (uint64, error)

Return a uint64 representation of the number, if possible. If not possible, err will be non-nil.

Jump to

Keyboard shortcuts

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