mathutil

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Dec 21, 2025 License: MIT Imports: 2 Imported by: 0

Documentation

Overview

Package mathutil provides mathematical and statistical operations on numeric slices.

The package uses Go generics to work with any numeric type (int, float64, etc.) through the Number constraint.

Aggregations

Basic mathematical operations on slices:

sum := mathutil.Sum([]int{1, 2, 3, 4, 5})      // 15
product := mathutil.Product([]int{1, 2, 3})   // 6
avg := mathutil.Average([]float64{1, 2, 3})   // 2.0

Statistics

Statistical functions:

median := mathutil.Median([]int{1, 2, 3, 4, 5})      // 3.0
mode := mathutil.Mode([]int{1, 2, 2, 3})             // [2]
stddev := mathutil.StdDev([]float64{1, 2, 3, 4, 5})  // ~1.41
variance := mathutil.Variance(data)

Extremes

Finding minimum and maximum values:

min, max := mathutil.MinMax([]int{3, 1, 4, 1, 5})
minIdx := mathutil.MinIndex(data)
maxIdx := mathutil.MaxIndex(data)

Number Theory

Prime numbers and related functions:

if mathutil.IsPrime(17) { ... }
primes := mathutil.Primes(100)
gcd := mathutil.GCD(12, 18)
lcm := mathutil.LCM(4, 6)

Matrix Operations

Basic matrix operations:

result := mathutil.MatrixMultiply(a, b)
transposed := mathutil.MatrixTranspose(m)

All functions are designed to handle edge cases gracefully, returning zero values or errors where appropriate.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrEmptySlice        = errors.New("empty slice")
	ErrDivisionByZero    = errors.New("division by zero")
	ErrInvalidDimensions = errors.New("invalid matrix dimensions")
	ErrNegativeInput     = errors.New("negative input not allowed")
)

Errors returned by math operations.

Functions

func Abs

func Abs[T Number](x T) T

Abs returns the absolute value of x.

func Add

func Add[T Number](a, b []T) []T

Add performs element-wise addition of two slices. The shorter slice determines the result length.

func Arange

func Arange[T Number](start, stop, step T) []T

Arange returns values from start to stop (exclusive) with given step.

func Average

func Average[T Number](s []T) float64

Average returns the arithmetic mean of the slice. Returns 0 for empty slices.

Example:

Average([]float64{1, 2, 3, 4, 5})  // 3.0

func Clamp

func Clamp[T Number](x, min, max T) T

Clamp restricts x to the range [min, max].

Example:

Clamp(15, 0, 10)  // 10
Clamp(-5, 0, 10)  // 0
Clamp(5, 0, 10)   // 5

func CosineSimilarity

func CosineSimilarity[T Number](a, b []T) float64

CosineSimilarity returns the cosine similarity between two vectors. Returns 0 if vectors have different lengths or either is zero vector.

func Cumsum

func Cumsum[T Number](s []T) []T

Cumsum returns the cumulative sum of the slice.

Example:

Cumsum([]int{1, 2, 3, 4})  // [1, 3, 6, 10]

func Diff

func Diff[T Number](s []T) []T

Diff returns the differences between consecutive elements.

Example:

Diff([]int{1, 3, 6, 10})  // [2, 3, 4]

func DotProduct

func DotProduct[T Number](a, b []T) T

DotProduct computes the dot product of two vectors. Returns 0 if vectors have different lengths.

func EuclideanDistance

func EuclideanDistance[T Number](a, b []T) float64

EuclideanDistance returns the Euclidean distance between two points.

func Factorial

func Factorial(n int) int64

Factorial returns n! (n factorial). Returns 1 for n <= 1. Returns 0 if result would overflow int64.

func Fibonacci

func Fibonacci(n int) int64

Fibonacci returns the nth Fibonacci number (0-indexed). F(0) = 0, F(1) = 1, F(n) = F(n-1) + F(n-2)

Example:

Fibonacci(10)  // 55

func GCD

func GCD[T Integer](a, b T) T

GCD returns the greatest common divisor of a and b using Euclidean algorithm.

Example:

GCD(12, 18)  // 6

func Histogram

func Histogram[T Number](data []T, bins []T) []int

Histogram returns the frequency count of values in bins. bins specifies the bin edges (n+1 edges for n bins).

func IQR

func IQR[T Number](s []T) float64

IQR returns the interquartile range (Q3 - Q1).

func IsPrime

func IsPrime[T Integer](n T) bool

IsPrime reports whether n is a prime number. Returns false for n < 2.

Example:

IsPrime(17)  // true
IsPrime(15)  // false

func LCM

func LCM[T Integer](a, b T) T

LCM returns the least common multiple of a and b.

Example:

LCM(4, 6)  // 12

func LinSpace

func LinSpace(start, end float64, n int) []float64

LinSpace returns n evenly spaced values from start to end (inclusive).

func Magnitude

func Magnitude[T Number](v []T) float64

Magnitude returns the Euclidean length of a vector.

func ManhattanDistance

func ManhattanDistance[T Number](a, b []T) T

ManhattanDistance returns the Manhattan (L1) distance between two points.

func Max

func Max[T Number](s []T) (T, error)

Max returns the maximum value in the slice. Returns zero value and ErrEmptySlice for empty slices.

func MaxIndex

func MaxIndex[T Number](s []T) int

MaxIndex returns the index of the maximum value. Returns -1 for empty slices.

func Median

func Median[T Number](s []T) float64

Median returns the middle value of a sorted slice. For even-length slices, returns the average of the two middle values. Returns 0 for empty slices.

Example:

Median([]int{1, 2, 3, 4, 5})  // 3.0
Median([]int{1, 2, 3, 4})    // 2.5

func Min

func Min[T Number](s []T) (T, error)

Min returns the minimum value in the slice. Returns zero value and ErrEmptySlice for empty slices.

func MinIndex

func MinIndex[T Number](s []T) int

MinIndex returns the index of the minimum value. Returns -1 for empty slices.

func MinMax

func MinMax[T Number](s []T) (min, max T, err error)

MinMax returns both minimum and maximum values in a single pass. Returns zero values and ErrEmptySlice for empty slices.

func Mode

func Mode[T Number](s []T) []T

Mode returns the most frequently occurring values. Returns nil for empty slices. May return multiple values if there are ties.

Example:

Mode([]int{1, 2, 2, 3, 3, 3})  // [3]
Mode([]int{1, 1, 2, 2})       // [1, 2] (tie)

func Multiply

func Multiply[T Number](a, b []T) []T

Multiply performs element-wise multiplication.

func Normalize

func Normalize[T Float](v []T) []T

Normalize returns a unit vector in the same direction. Returns nil if the input is a zero vector.

func Percentile

func Percentile[T Number](s []T, p float64) float64

Percentile returns the value at the given percentile (0-100). Uses linear interpolation between data points. Returns 0 for empty slices.

Example:

Percentile([]int{1, 2, 3, 4, 5}, 50)  // 3.0 (median)

func Pow

func Pow[T Number](x T, n int) T

Pow returns x raised to the power of n. For negative exponents with integer types, returns 0.

func PowFloat

func PowFloat(x float64, n int) float64

PowFloat returns x raised to the power of n for float types.

func Primes

func Primes(n int) []int

Primes returns all prime numbers up to and including n. Uses the Sieve of Eratosthenes.

Example:

Primes(20)  // [2, 3, 5, 7, 11, 13, 17, 19]

func Product

func Product[T Number](s []T) T

Product returns the product of all elements in the slice. Returns 1 for empty slices.

Example:

Product([]int{1, 2, 3, 4})  // 24

func Quartiles

func Quartiles[T Number](s []T) (q1, q2, q3 float64)

Quartiles returns Q1, Q2 (median), and Q3.

func Range

func Range[T Number](s []T) (T, error)

Range returns the difference between max and min values. Returns 0 and ErrEmptySlice for empty slices.

func SampleStdDev

func SampleStdDev[T Number](s []T) float64

SampleStdDev returns the sample standard deviation. Returns 0 for slices with fewer than 2 elements.

func SampleVariance

func SampleVariance[T Number](s []T) float64

SampleVariance returns the sample variance (using N-1 denominator). Returns 0 for slices with fewer than 2 elements.

func Scale

func Scale[T Number](s []T, scalar T) []T

Scale multiplies all elements by a scalar and returns a new slice.

func Sign

func Sign[T Number](x T) int

Sign returns -1 for negative, 0 for zero, 1 for positive.

func Sqrt

func Sqrt(x float64) float64

Sqrt returns the square root using Newton's method. Returns 0 for negative numbers.

func StdDev

func StdDev[T Number](s []T) float64

StdDev returns the population standard deviation. Returns 0 for empty slices.

func Subtract

func Subtract[T Number](a, b []T) []T

Subtract performs element-wise subtraction (a - b).

func Sum

func Sum[T Number](s []T) T

Sum returns the sum of all elements in the slice. Returns 0 for empty slices.

Example:

Sum([]int{1, 2, 3, 4, 5})  // 15

func Variance

func Variance[T Number](s []T) float64

Variance returns the population variance of the slice. Returns 0 for empty slices.

For sample variance (N-1 denominator), use SampleVariance.

Types

type Float

type Float interface {
	~float32 | ~float64
}

Float is a constraint for floating-point types.

type Integer

type Integer interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64 |
		~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
}

Integer is a constraint for all integer types.

type Matrix

type Matrix[T Number] [][]T

Matrix represents a 2D matrix.

func MatrixAdd

func MatrixAdd[T Number](a, b Matrix[T]) (Matrix[T], error)

MatrixAdd adds two matrices element-wise.

func MatrixMultiply

func MatrixMultiply[T Number](a, b Matrix[T]) (Matrix[T], error)

MatrixMultiply multiplies two matrices. Returns nil and ErrInvalidDimensions if dimensions don't match.

Matrix A (m×n) × Matrix B (n×p) = Matrix C (m×p).

func MatrixScalar

func MatrixScalar[T Number](m Matrix[T], scalar T) Matrix[T]

MatrixScalar multiplies a matrix by a scalar.

func MatrixTranspose

func MatrixTranspose[T Number](m Matrix[T]) Matrix[T]

MatrixTranspose returns the transpose of a matrix.

type Number

type Number interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64 |
		~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr |
		~float32 | ~float64
}

Number is a constraint for all numeric types.

Jump to

Keyboard shortcuts

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