gomath

package module
v1.1.1 Latest Latest
Warning

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

Go to latest
Published: Sep 13, 2026 License: MIT Imports: 3 Imported by: 0

README

math

CI CodeQL Coverage Mutation Documentation Go Reference Release Go License

math is an immutable arbitrary-precision numeric foundation for Go. It provides distinct APIs for signed integers, exact rationals, finite base-10 decimals, and explicitly inexact binary floats. Use ordinary Go numeric types when their fixed width and machine arithmetic are sufficient.

The root module is stable at v1 and requires Go 1.27.0 or newer. Install the current minor release with:

go get github.com/faustbrian/go-math@v1.1.0

The root package identifier intentionally remains gomath, avoiding a collision with the standard-library math package. This is a compatibility exception, not an adapter naming pattern.

amount := decimal.MustParse("19.995")
result, err := amount.Quantize(
	context.Background(), 2, decimal.HalfEven, gomath.DefaultLimits(),
)

All constructors copy mutable math/big inputs. Operations return new values, accessors return copies, JSON uses strings, and potentially expensive work is bounded by gomath.Limits. Decimal contexts make precision, exponent range, rounding, conditions, and traps explicit. No conversion passes through float64.

See the executable examples, documentation index, specification decisions, cookbook, and verification guide. See the versioned Golib ecosystem index and package-family selection guidance for the shared design language this module follows.

Packages

  • integer: exact signed integer arithmetic, roots, GCD/LCM, and unbiased injected-source random values.
  • rational: normalized exact fractions and bounded decimal conversion.
  • decimal: finite coefficient/exponent values, exact operations, and context-rounded operations with conditions.
  • bigfloat: explicit precision and rounding around math/big.Float.
  • encoding: deterministic versioned binary codecs.
  • mathtest: reusable algebraic-law and round-trip assertions.

Development

Run make cohesion for the repository-owned cohesion contract, make check for package gates, and make ci for the complete repository contract. See CHANGELOG.md for releases and SECURITY.md for vulnerability reporting. Use SUPPORT.md for support and troubleshooting for operational diagnosis.

Licensed under MIT.

Documentation

Use the documentation index for package-owned guides, operational contracts, examples, and maintainer references.

Documentation

Overview

Package gomath defines contracts shared by the numeric subpackages.

Example (Decimal)
package main

import (
	"context"
	"fmt"

	gomath "github.com/faustbrian/go-math"
	"github.com/faustbrian/go-math/decimal"
)

func main() {
	price := decimal.MustParse("19.995")
	result, _ := price.Quantize(
		context.Background(), 2, gomath.RoundHalfEven, gomath.DefaultLimits(),
	)
	fmt.Println(result.Value, result.Conditions)
}
Output:
20.00 rounded,inexact
Example (Integer)
package main

import (
	"context"
	"fmt"

	gomath "github.com/faustbrian/go-math"
	"github.com/faustbrian/go-math/integer"
)

func main() {
	value, _ := integer.Parse("ff", integer.ParseOptions{
		Base: 16, Limits: gomath.DefaultLimits(),
	})
	result, _ := value.Mul(context.Background(), integer.New(2), gomath.DefaultLimits())
	fmt.Println(result)
}
Output:
510

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidArgument reports an invalid option or operation argument.
	ErrInvalidArgument = errors.New("math: invalid argument")
	// ErrInvalidSyntax reports input outside a type's strict grammar.
	ErrInvalidSyntax = errors.New("math: invalid syntax")
	// ErrLimitExceeded reports work rejected by an explicit resource bound.
	ErrLimitExceeded = errors.New("math: resource limit exceeded")
	// ErrDivisionByZero reports division by numeric zero.
	ErrDivisionByZero = errors.New("math: division by zero")
	// ErrDomain reports an operation outside its mathematical domain.
	ErrDomain = errors.New("math: domain error")
	// ErrConversion reports a conversion that cannot be exact.
	ErrConversion = errors.New("math: inexact conversion")
	// ErrOverflow reports a result outside an explicitly bounded range.
	ErrOverflow = errors.New("math: overflow")
	// ErrUnderflow reports a nonzero result below an explicitly bounded range.
	ErrUnderflow = errors.New("math: underflow")
	// ErrTrappedCondition reports a decimal or floating-point condition selected
	// by an operation context's trap mask.
	ErrTrappedCondition = errors.New("math: trapped condition")
)
View Source
var ErrRandomSource = errors.New("math: random source failed")

ErrRandomSource reports a failure from a caller-provided random source.

Functions

This section is empty.

Types

type Condition

type Condition uint16

Condition is a bit set of arithmetic conditions.

const (
	ConditionRounded Condition = 1 << iota
	ConditionInexact
	ConditionOverflow
	ConditionUnderflow
	ConditionDivisionByZero
	ConditionInvalidOperation
	ConditionClamped
	ConditionSubnormal
)

func (Condition) Has

func (c Condition) Has(wanted Condition) bool

Has reports whether every bit in wanted is present.

func (Condition) String

func (c Condition) String() string

String returns stable comma-separated condition names.

type Limits

type Limits struct {
	MaxInputDigits       int
	MaxOutputDigits      int
	MaxExponentMagnitude int32
	MaxPrecision         uint32
	MaxPowerExponent     uint64
	MaxRootDegree        uint32
	MaxRandomBits        int
	MaxRandomAttempts    int
	MaxIntermediateBits  int
	MaxDecimalExpansion  int
	// MaxDiagnosticBytes is retained for v1 source compatibility.
	// Deprecated: reserved no-op; stable category strings are fixed and bounded.
	MaxDiagnosticBytes int
}

Limits bounds parsing, formatting, and potentially expensive arithmetic. It is copied by value and contains no mutable shared state.

func DefaultLimits

func DefaultLimits() Limits

DefaultLimits returns conservative general-purpose resource bounds.

func (Limits) Validate

func (l Limits) Validate() error

Validate reports whether every limit is positive.

type RoundingMode

type RoundingMode uint8

RoundingMode selects how a discarded nonzero remainder affects a result.

const (
	RoundHalfEven RoundingMode = iota
	RoundHalfUp
	RoundHalfDown
	RoundDown
	RoundUp
	RoundCeiling
	RoundFloor
)

func (RoundingMode) String

func (r RoundingMode) String() string

String returns the stable configuration name of r.

func (RoundingMode) Valid

func (r RoundingMode) Valid() bool

Valid reports whether r is a supported rounding mode.

Directories

Path Synopsis
Package bigfloat provides immutable arbitrary-precision binary floating-point values.
Package bigfloat provides immutable arbitrary-precision binary floating-point values.
Package decimal provides immutable finite base-10 decimals with explicit precision, rounding, exponent, trap, condition, and resource policies.
Package decimal provides immutable finite base-10 decimals with explicit precision, rounding, exponent, trap, condition, and resource policies.
Package encoding provides optional deterministic codecs for math values.
Package encoding provides optional deterministic codecs for math values.
Package integer provides immutable arbitrary-precision signed integers.
Package integer provides immutable arbitrary-precision signed integers.
Package mathtest provides reusable assertions for numeric laws and codecs.
Package mathtest provides reusable assertions for numeric laws and codecs.
Package rational provides immutable exact fractions.
Package rational provides immutable exact fractions.

Jump to

Keyboard shortcuts

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