math

package
v0.0.0-...-0d087c0 Latest Latest
Warning

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

Go to latest
Published: Aug 17, 2025 License: MIT Imports: 7 Imported by: 0

Documentation

Overview

Package math provides mathematical functions and operations for GoNP arrays.

Overview

The math package extends Go's standard math library to work with GoNP arrays, providing vectorized mathematical operations, linear algebra functions, and universal functions (ufuncs) that operate element-wise on arrays.

All functions in this package are optimized for performance using:

  • SIMD instructions (AVX, AVX2, AVX-512) where available
  • Multi-threading for large arrays
  • Efficient memory access patterns
  • Automatic broadcasting for compatible shapes

Quick Start

Basic mathematical operations:

import "github.com/julianshen/gonp/array"
import "github.com/julianshen/gonp/math"

// Create test data
arr, _ := array.FromSlice([]float64{1, 2, 3, 4, 5})

// Universal functions (element-wise operations)
sines := math.Sin(arr)           // Sine of each element
exponentials := math.Exp(arr)    // e^x for each element
logarithms := math.Log(arr)      // Natural log of each element

// Power and root functions
squares := math.Square(arr)      // x^2 for each element
roots := math.Sqrt(arr)          // √x for each element
powers := math.Pow(arr, 2.5)     // x^2.5 for each element

// Rounding functions
rounded := math.Round(arr)       // Round to nearest integer
ceiling := math.Ceil(arr)        // Round up
floor := math.Floor(arr)         // Round down

Universal Functions (UFuncs)

Universal functions operate element-wise on arrays and support broadcasting:

## Trigonometric Functions

// Basic trigonometric functions
sines := math.Sin(angles)        // Sine
cosines := math.Cos(angles)      // Cosine
tangents := math.Tan(angles)     // Tangent

// Inverse trigonometric functions
arcsines := math.Asin(values)    // Arcsine
arccosines := math.Acos(values)  // Arccosine
arctangents := math.Atan(values) // Arctangent
atan2_vals := math.Atan2(y, x)   // Two-argument arctangent

// Hyperbolic functions
sinh_vals := math.Sinh(arr)      // Hyperbolic sine
cosh_vals := math.Cosh(arr)      // Hyperbolic cosine
tanh_vals := math.Tanh(arr)      // Hyperbolic tangent

## Exponential and Logarithmic Functions

// Exponential functions
exp_vals := math.Exp(arr)        // e^x
exp2_vals := math.Exp2(arr)      // 2^x
expm1_vals := math.Expm1(arr)    // e^x - 1 (accurate for small x)

// Logarithmic functions
log_vals := math.Log(arr)        // Natural logarithm
log10_vals := math.Log10(arr)    // Base-10 logarithm
log2_vals := math.Log2(arr)      // Base-2 logarithm
log1p_vals := math.Log1p(arr)    // ln(1+x) (accurate for small x)

## Power and Root Functions

// Power functions
squares := math.Square(arr)      // x^2
cubes := math.Power(arr, 3)      // x^3
powers := math.Pow(base, exp)    // base^exp (element-wise)

// Root functions
sqrt_vals := math.Sqrt(arr)      // Square root
cbrt_vals := math.Cbrt(arr)      // Cube root

## Rounding and Comparison Functions

// Rounding
rounded := math.Round(arr)       // Round to nearest integer
truncated := math.Trunc(arr)     // Truncate toward zero
ceiling := math.Ceil(arr)        // Round up
floor := math.Floor(arr)         // Round down

// Comparison and selection
maximums := math.Maximum(a, b)   // Element-wise maximum
minimums := math.Minimum(a, b)   // Element-wise minimum
absolute := math.Abs(arr)        // Absolute value
signs := math.Sign(arr)          // Sign of each element

Linear Algebra Functions

The package provides comprehensive linear algebra operations:

## Matrix Operations

// Matrix multiplication
result := math.Dot(a, b)         // Matrix multiplication
inner := math.Inner(a, b)        // Inner product
outer := math.Outer(a, b)        // Outer product

// Matrix properties
det := math.Det(matrix)          // Determinant
trace := math.Trace(matrix)      // Trace (sum of diagonal)
rank := math.Rank(matrix)        // Matrix rank
cond := math.Cond(matrix)        // Condition number

// Matrix norms
frobenius := math.Norm(matrix)           // Frobenius norm
spectral := math.Norm(matrix, "spec")    // Spectral norm
nuclear := math.Norm(matrix, "nuc")      // Nuclear norm

## Matrix Decompositions

// Singular Value Decomposition
u, s, vt := math.SVD(matrix)     // SVD: A = U * S * V^T

// QR Decomposition
q, r := math.QR(matrix)          // QR: A = Q * R

// Cholesky Decomposition
l := math.Cholesky(matrix)       // A = L * L^T (for positive definite)

// LU Decomposition with pivoting
p, l, u := math.LU(matrix)       // PA = LU

// Eigenvalue Decomposition
eigenvals, eigenvecs := math.Eig(matrix)  // A * v = λ * v

## Linear System Solving

// Solve linear systems Ax = b
solution := math.Solve(A, b)     // Solve Ax = b

// Least squares solutions
x, residuals := math.LstSq(A, b) // Minimize ||Ax - b||^2

// Matrix inversion
inverse := math.Inv(matrix)      // A^(-1)
pinverse := math.Pinv(matrix)    // Moore-Penrose pseudoinverse

Polynomial Operations

Complete polynomial algebra and root finding:

// Create polynomials
p := math.NewPolynomial([]float64{1, -2, 1})  // x^2 - 2x + 1

// Polynomial operations
sum := p.Add(q)                  // Polynomial addition
product := p.Multiply(q)         // Polynomial multiplication
quotient, remainder := p.Divide(q) // Polynomial division
composed := p.Compose(q)         // Composition: p(q(x))

// Evaluation and root finding
values := p.Evaluate(x_vals)     // Evaluate at array of points
derivative := p.Derivative()     // First derivative
integral := p.Integral()         // Indefinite integral
roots := p.Roots()               // Find polynomial roots

// Polynomial fitting
coeffs := math.PolyFit(x, y, degree)  // Fit polynomial to data

Performance Features

## SIMD Optimization

Mathematical functions automatically use SIMD instructions when available:

  • Operates on 4 float64 values simultaneously with AVX
  • Up to 8 float64 values with AVX-512
  • 2-4x performance improvement over scalar operations
  • Automatic fallback for unsupported operations

## Memory Efficiency

// In-place operations (when possible)
math.SinInPlace(arr)             // Modifies arr directly
math.ExpInPlace(arr)             // Saves memory allocation

// Pre-allocated output arrays
result := array.Empty(arr.Shape(), arr.DType())
math.Sin(arr, result)            // Store result in existing array

## Broadcasting

Operations between arrays of different but compatible shapes:

matrix, _ := array.FromSlice([][]float64{{1, 2, 3}, {4, 5, 6}})  // [2, 3]
vector, _ := array.FromSlice([]float64{10, 20, 30})              // [3]
result, _ := matrix.Add(vector)     // Broadcasting: vector applied to each row

Error Handling

Mathematical functions handle edge cases appropriately:

// Domain errors
result := math.Sqrt(negative_array)  // Returns NaN for negative inputs
logs := math.Log(zero_array)         // Returns -Inf for zero inputs

// Overflow/underflow
large := math.Exp(very_large_array)  // Returns +Inf for overflow
small := math.Exp(very_small_array)  // Returns 0 for underflow

// Invalid operations
result, err := math.Solve(singular_matrix, b)  // Returns error
if err != nil {
	log.Printf("Matrix is singular: %v", err)
}

Advanced Usage

## Custom Universal Functions

// Define custom element-wise functions
sigmoid := func(x interface{}) interface{} {
	val := x.(float64)
	return 1.0 / (1.0 + math.Exp(-val))
}

// Apply to arrays
result := math.ApplyUnary(arr, sigmoid)

## Numerical Stability

The package includes numerically stable implementations:

  • Expm1/Log1p for accurate computation near zero
  • Kahan summation for reduced floating-point errors
  • Pivoting in matrix decompositions
  • Condition number checking for ill-conditioned matrices

## Integration with Statistics

// Mathematical functions work seamlessly with stats package
data := generateRandomData()
transformed := math.Log(data)        // Log transform
normalized := stats.Normalize(transformed)  // Z-score normalization
correlation := stats.Correlation(data, transformed)

Migration from NumPy

Common NumPy mathematical functions and their GoNP equivalents:

# NumPy                          // GoNP
import numpy as np               import "github.com/julianshen/gonp/math"

np.sin(arr)                      math.Sin(arr)
np.exp(arr)                      math.Exp(arr)
np.sqrt(arr)                     math.Sqrt(arr)
np.power(arr, 2)                 math.Pow(arr, 2)

np.dot(a, b)                     math.Dot(a, b)
np.linalg.svd(matrix)            math.SVD(matrix)
np.linalg.solve(A, b)            math.Solve(A, b)
np.linalg.inv(matrix)            math.Inv(matrix)

np.polyfit(x, y, deg)            math.PolyFit(x, y, deg)
np.roots(coeffs)                 math.NewPolynomial(coeffs).Roots()

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Abs

func Abs(arr *array.Array) (*array.Array, error)

Abs computes the absolute value of array elements

func AbsInPlace

func AbsInPlace(arr *array.Array) error

AbsInPlace computes the absolute value of array elements in-place

func Acos

func Acos(arr *array.Array) (*array.Array, error)

Acos computes the arccosine of array elements

func AcosInPlace

func AcosInPlace(arr *array.Array) error

AcosInPlace computes the arccosine of array elements in-place

func Acosh

func Acosh(arr *array.Array) (*array.Array, error)

Acosh computes the inverse hyperbolic cosine of array elements

func AcoshInPlace

func AcoshInPlace(arr *array.Array) error

AcoshInPlace computes the inverse hyperbolic cosine of array elements in-place

func ApplyBinary

func ApplyBinary(a, b *array.Array, fn BinaryFunc) (*array.Array, error)

ApplyBinary applies a binary universal function to two arrays with broadcasting

func ApplyUnary

func ApplyUnary(arr *array.Array, fn UnaryFunc) (*array.Array, error)

ApplyUnary applies a unary universal function to an array

func ApplyUnaryInPlace

func ApplyUnaryInPlace(arr *array.Array, fn UnaryFunc) error

ApplyUnaryInPlace applies a unary universal function to an array in-place

func Asin

func Asin(arr *array.Array) (*array.Array, error)

Asin computes the arcsine of array elements

func AsinInPlace

func AsinInPlace(arr *array.Array) error

AsinInPlace computes the arcsine of array elements in-place

func Asinh

func Asinh(arr *array.Array) (*array.Array, error)

Asinh computes the inverse hyperbolic sine of array elements

func AsinhInPlace

func AsinhInPlace(arr *array.Array) error

AsinhInPlace computes the inverse hyperbolic sine of array elements in-place

func Atan

func Atan(arr *array.Array) (*array.Array, error)

Atan computes the arctangent of array elements

func Atan2

func Atan2(y, x *array.Array) (*array.Array, error)

Atan2 computes the two-argument arctangent of y/x element-wise.

This function computes atan2(y, x) = atan(y/x) element-wise, but handles the signs of both arguments to determine the correct quadrant. This is essential for converting Cartesian coordinates to polar coordinates.

Mathematical Definition: atan2(y, x) for corresponding elements y[i], x[i]

Performance:

  • SIMD-optimized for large arrays
  • Broadcasting supported for compatible shapes
  • Handles edge cases correctly (zeros, infinities)

Input Domain:

  • Both arrays: Real numbers (any finite values, zeros, infinities)
  • Arrays must have compatible shapes for broadcasting

Output Range: [-π, π] radians

Example:

// Convert Cartesian to polar coordinates
x_coords, _ := array.FromSlice([]float64{1, -1, -1, 1})
y_coords, _ := array.FromSlice([]float64{1, 1, -1, -1})
angles, _ := math.Atan2(y_coords, x_coords)
// Result: [π/4, 3π/4, -3π/4, -π/4] (quadrant-aware)

// Broadcasting with scalar
y_vals, _ := array.FromSlice([]float64{0, 1, 2, 3})
x_scalar, _ := array.FromSlice([]float64{1})
angles, _ := math.Atan2(y_vals, x_scalar)  // Broadcasting

Special Cases:

  • atan2(+0, +0) = +0
  • atan2(-0, +0) = -0
  • atan2(+0, -0) = +π
  • atan2(-0, -0) = -π
  • atan2(+∞, +∞) = +π/4
  • atan2(-∞, -∞) = -3π/4

Returns an error if either input array is nil or shapes are incompatible.

func AtanInPlace

func AtanInPlace(arr *array.Array) error

AtanInPlace computes the arctangent of array elements in-place

func Atanh

func Atanh(arr *array.Array) (*array.Array, error)

Atanh computes the inverse hyperbolic tangent of array elements

func AtanhInPlace

func AtanhInPlace(arr *array.Array) error

AtanhInPlace computes the inverse hyperbolic tangent of array elements in-place

func Cbrt

func Cbrt(arr *array.Array) (*array.Array, error)

Cbrt computes the cube root of array elements

func CbrtInPlace

func CbrtInPlace(arr *array.Array) error

CbrtInPlace computes the cube root of array elements in-place

func Ceil

func Ceil(arr *array.Array) (*array.Array, error)

Ceil returns the ceiling of array elements (smallest integer >= x)

func CeilInPlace

func CeilInPlace(arr *array.Array) error

CeilInPlace returns the ceiling of array elements in-place

func Chol

func Chol(arr *array.Array) (*array.Array, error)

Chol computes the Cholesky decomposition of a positive definite matrix A = L*L^T

func Clip

func Clip(arr *array.Array, min, max float64) (*array.Array, error)

Clip clips array values to be within [min, max] range

func ClipInPlace

func ClipInPlace(arr *array.Array, min, max float64) error

ClipInPlace clips array values to be within [min, max] range in-place

func CompensatedDotProduct

func CompensatedDotProduct(a, b *array.Array) (float64, error)

CompensatedDotProduct computes dot product with Kahan summation for better precision

func CompensatedNorm

func CompensatedNorm(a *array.Array) (float64, error)

CompensatedNorm computes the L2 norm with enhanced numerical stability

func ConditionNumber

func ConditionNumber(arr *array.Array) (float64, error)

ConditionNumber computes the condition number of a matrix using SVD Returns the ratio of largest to smallest singular value

func Copysign

func Copysign(x, y *array.Array) (*array.Array, error)

Copysign returns array with elements having the magnitude of x and the sign of y

func Cos

func Cos(arr *array.Array) (*array.Array, error)

Cos computes the cosine of array elements

func CosInPlace

func CosInPlace(arr *array.Array) error

CosInPlace computes the cosine of array elements in-place

func Cosh

func Cosh(arr *array.Array) (*array.Array, error)

Cosh computes the hyperbolic cosine of array elements

func CoshInPlace

func CoshInPlace(arr *array.Array) error

CoshInPlace computes the hyperbolic cosine of array elements in-place

func Deg2Rad

func Deg2Rad(arr *array.Array) (*array.Array, error)

Deg2Rad converts degrees to radians

func Deg2RadInPlace

func Deg2RadInPlace(arr *array.Array) error

Deg2RadInPlace converts degrees to radians in-place

func Det

func Det(arr *array.Array) (float64, error)

Det computes the determinant of a square matrix

func Dot

func Dot(a, b *array.Array) (*array.Array, error)

Dot computes the dot product of two arrays For 1-D arrays, it computes the inner product For 2-D arrays, it computes matrix multiplication

func Exp

func Exp(arr *array.Array) (*array.Array, error)

Exp computes the exponential of array elements

func Exp2

func Exp2(arr *array.Array) (*array.Array, error)

Exp2 computes 2^x for array elements

func Exp2InPlace

func Exp2InPlace(arr *array.Array) error

Exp2InPlace computes 2^x for array elements in-place

func Exp10

func Exp10(arr *array.Array) (*array.Array, error)

Exp10 computes 10^x for array elements

func Exp10InPlace

func Exp10InPlace(arr *array.Array) error

Exp10InPlace computes 10^x for array elements in-place

func ExpInPlace

func ExpInPlace(arr *array.Array) error

ExpInPlace computes the exponential of array elements in-place

func Expm1

func Expm1(arr *array.Array) (*array.Array, error)

Expm1 computes exp(x) - 1 for array elements

func Expm1InPlace

func Expm1InPlace(arr *array.Array) error

Expm1InPlace computes exp(x) - 1 for array elements in-place

func ExtendedPrecisionSum

func ExtendedPrecisionSum(a *array.Array) (float64, error)

ExtendedPrecisionSum uses extended precision arithmetic for critical summations This uses a form of double-double arithmetic for even better precision

func Fix

func Fix(arr *array.Array) (*array.Array, error)

Fix rounds array elements towards zero (same as Trunc)

func FixInPlace

func FixInPlace(arr *array.Array) error

FixInPlace rounds array elements towards zero in-place

func Floor

func Floor(arr *array.Array) (*array.Array, error)

Floor returns the floor of array elements (largest integer <= x)

func FloorInPlace

func FloorInPlace(arr *array.Array) error

FloorInPlace returns the floor of array elements in-place

func Fmod

func Fmod(x, y *array.Array) (*array.Array, error)

Fmod computes the floating-point remainder of x/y element-wise

func Hypot

func Hypot(x, y *array.Array) (*array.Array, error)

Hypot computes the Euclidean norm, sqrt(x*x + y*y), element-wise

func KahanMean

func KahanMean(a *array.Array) (float64, error)

KahanMean computes the mean using Kahan summation for better precision

func KahanStandardDeviation

func KahanStandardDeviation(a *array.Array, ddof int) (float64, error)

KahanStandardDeviation computes standard deviation using Kahan-based variance

func KahanSum

func KahanSum(a *array.Array) (float64, error)

KahanSum performs Kahan summation algorithm on an array This provides much better numerical stability than naive summation for large arrays

func KahanVariance

func KahanVariance(a *array.Array, ddof int) (float64, error)

KahanVariance computes variance using Kahan summation for numerical stability Uses the two-pass algorithm with compensated summation

func Log

func Log(arr *array.Array) (*array.Array, error)

Log computes the natural logarithm of array elements

func Log1p

func Log1p(arr *array.Array) (*array.Array, error)

Log1p computes log(1 + x) for array elements

func Log1pInPlace

func Log1pInPlace(arr *array.Array) error

Log1pInPlace computes log(1 + x) for array elements in-place

func Log2

func Log2(arr *array.Array) (*array.Array, error)

Log2 computes the base-2 logarithm of array elements

func Log2InPlace

func Log2InPlace(arr *array.Array) error

Log2InPlace computes the base-2 logarithm of array elements in-place

func Log10

func Log10(arr *array.Array) (*array.Array, error)

Log10 computes the base-10 logarithm of array elements

func Log10InPlace

func Log10InPlace(arr *array.Array) error

Log10InPlace computes the base-10 logarithm of array elements in-place

func LogInPlace

func LogInPlace(arr *array.Array) error

LogInPlace computes the natural logarithm of array elements in-place

func Logb

func Logb(arr *array.Array) (*array.Array, error)

Logb computes the binary logarithm of array elements

func LogbInPlace

func LogbInPlace(arr *array.Array) error

LogbInPlace computes the binary logarithm of array elements in-place

func MatMul

func MatMul(a, b *array.Array) (*array.Array, error)

MatMul performs matrix multiplication with broadcasting support

func Maximum

func Maximum(a, b *array.Array) (*array.Array, error)

Maximum computes the element-wise maximum of two arrays

func Minimum

func Minimum(a, b *array.Array) (*array.Array, error)

Minimum computes the element-wise minimum of two arrays

func NeumaierSum

func NeumaierSum(a *array.Array) (float64, error)

NeumaierSum implements Neumaier's improved Kahan summation algorithm This is even more accurate than standard Kahan summation for certain cases

func Norm

func Norm(arr *array.Array, ord interface{}) (float64, error)

Norm computes various norms of an array

func PairwiseSum

func PairwiseSum(a *array.Array) (float64, error)

PairwiseSum implements pairwise summation for improved numerical stability This algorithm has O(log n) error accumulation instead of O(n) for naive summation

func Power

func Power(x, y *array.Array) (*array.Array, error)

Power computes x^y element-wise

func PowerScalar

func PowerScalar(arr *array.Array, scalar float64) (*array.Array, error)

PowerScalar computes x^scalar for array elements

func PowerScalarInPlace

func PowerScalarInPlace(arr *array.Array, scalar float64) error

PowerScalarInPlace computes x^scalar for array elements in-place

func Rad2Deg

func Rad2Deg(arr *array.Array) (*array.Array, error)

Rad2Deg converts radians to degrees

func Rad2DegInPlace

func Rad2DegInPlace(arr *array.Array) error

Rad2DegInPlace converts radians to degrees in-place

func Rank

func Rank(arr *array.Array, tolerance float64) (int, error)

Rank computes the numerical rank of a matrix using SVD

func Reciprocal

func Reciprocal(arr *array.Array) (*array.Array, error)

Reciprocal computes 1/x for array elements

func ReciprocalInPlace

func ReciprocalInPlace(arr *array.Array) error

ReciprocalInPlace computes 1/x for array elements in-place

func Remainder

func Remainder(x, y *array.Array) (*array.Array, error)

Remainder computes the IEEE remainder of x/y element-wise

func Rint

func Rint(arr *array.Array) (*array.Array, error)

Rint rounds array elements to nearest integer (using current rounding mode)

func RintInPlace

func RintInPlace(arr *array.Array) error

RintInPlace rounds array elements to nearest integer in-place

func Round

func Round(arr *array.Array) (*array.Array, error)

Round rounds array elements to the nearest integer

func RoundInPlace

func RoundInPlace(arr *array.Array) error

RoundInPlace rounds array elements to the nearest integer in-place

func RoundN

func RoundN(arr *array.Array, n int) (*array.Array, error)

RoundN rounds array elements to n decimal places

func RoundNInPlace

func RoundNInPlace(arr *array.Array, n int) error

RoundNInPlace rounds array elements to n decimal places in-place

func Sign

func Sign(arr *array.Array) (*array.Array, error)

Sign returns the sign of array elements (-1, 0, or 1)

func SignInPlace

func SignInPlace(arr *array.Array) error

SignInPlace returns the sign of array elements in-place

func Sin

func Sin(arr *array.Array) (*array.Array, error)

Sin computes the sine of array elements using SIMD-optimized universal functions.

This function applies the sine function element-wise to all elements in the array. It supports both real and complex number arrays, with automatic type handling.

Mathematical Definition: sin(x) for each element x in the array

Performance:

  • SIMD-optimized for large arrays (>32 elements)
  • Supports complex numbers with full precision
  • Thread-safe for concurrent use

Input Domain:

  • Real numbers: All values (angle in radians)
  • Complex numbers: All values

Output Range:

  • Real numbers: [-1, 1]
  • Complex numbers: Complex plane

Example:

// Compute sine of angles
angles, _ := array.FromSlice([]float64{0, math.Pi/6, math.Pi/4, math.Pi/3, math.Pi/2})
sines, _ := math.Sin(angles)
// Result: [0, 0.5, 0.707..., 0.866..., 1]

// Complex sine
complex_arr, _ := array.FromSlice([]complex128{1+2i, 2+3i})
complex_sines, _ := math.Sin(complex_arr)

Special Values:

  • Sin(0) = 0
  • Sin(π/2) = 1
  • Sin(π) = 0 (within floating-point precision)
  • Sin(NaN) = NaN
  • Sin(±Inf) = NaN

Returns an error if the input array is nil.

func SinInPlace

func SinInPlace(arr *array.Array) error

SinInPlace computes the sine of array elements in-place

func Sinh

func Sinh(arr *array.Array) (*array.Array, error)

Sinh computes the hyperbolic sine of array elements

func SinhInPlace

func SinhInPlace(arr *array.Array) error

SinhInPlace computes the hyperbolic sine of array elements in-place

func Solve

func Solve(A, b *array.Array) (*array.Array, error)

Solve solves the linear system Ax = b using appropriate decomposition

func Sqrt

func Sqrt(arr *array.Array) (*array.Array, error)

Sqrt computes the square root of array elements

func SqrtInPlace

func SqrtInPlace(arr *array.Array) error

SqrtInPlace computes the square root of array elements in-place

func Square

func Square(arr *array.Array) (*array.Array, error)

Square computes the square of array elements

func SquareInPlace

func SquareInPlace(arr *array.Array) error

SquareInPlace computes the square of array elements in-place

func Tan

func Tan(arr *array.Array) (*array.Array, error)

Tan computes the tangent of array elements

func TanInPlace

func TanInPlace(arr *array.Array) error

TanInPlace computes the tangent of array elements in-place

func Tanh

func Tanh(arr *array.Array) (*array.Array, error)

Tanh computes the hyperbolic tangent of array elements

func TanhInPlace

func TanhInPlace(arr *array.Array) error

TanhInPlace computes the hyperbolic tangent of array elements in-place

func Trace

func Trace(arr *array.Array) (interface{}, error)

Trace computes the sum of the diagonal elements of a 2-D array

func Transpose

func Transpose(arr *array.Array) (*array.Array, error)

Transpose returns the transpose of a 2-D array or swaps the last two axes for higher dimensions

func Trunc

func Trunc(arr *array.Array) (*array.Array, error)

Trunc truncates array elements to integer (towards zero)

func TruncInPlace

func TruncInPlace(arr *array.Array) error

TruncInPlace truncates array elements to integer in-place

Types

type ArithmeticOps

type ArithmeticOps interface {
	// Add performs element-wise addition with broadcasting
	Add(other *array.Array) (*array.Array, error)

	// Sub performs element-wise subtraction with broadcasting
	Sub(other *array.Array) (*array.Array, error)

	// Mul performs element-wise multiplication with broadcasting
	Mul(other *array.Array) (*array.Array, error)

	// Div performs element-wise division with broadcasting
	Div(other *array.Array) (*array.Array, error)

	// Mod performs element-wise modulo with broadcasting
	Mod(other *array.Array) (*array.Array, error)

	// Pow performs element-wise power with broadcasting
	Pow(other *array.Array) (*array.Array, error)
}

ArithmeticOps defines element-wise arithmetic operations interface

type ArrayManipulationOps

type ArrayManipulationOps interface {
	// Concatenate joins arrays along existing axis
	Concatenate(other *array.Array, axis int) (*array.Array, error)

	// Stack joins arrays along new axis
	Stack(other *array.Array, axis int) (*array.Array, error)

	// Split divides array into sub-arrays
	Split(indices []int, axis int) ([]*array.Array, error)

	// Squeeze removes single-dimensional entries
	Squeeze(axis ...int) (*array.Array, error)

	// ExpandDims expands array dimensions
	ExpandDims(axis int) (*array.Array, error)

	// Flatten returns a flattened copy of the array
	Flatten() *array.Array

	// Ravel returns a flattened view of the array if possible
	Ravel() (*array.Array, error)
}

ArrayManipulationOps defines array manipulation operations interface

type BinaryFunc

type BinaryFunc func(x, y interface{}) interface{}

BinaryFunc represents a universal function that operates on two arrays

type BroadcastingOps

type BroadcastingOps interface {
	// BroadcastTo broadcasts array to specified shape
	BroadcastTo(shape []int) (*array.Array, error)

	// CanBroadcast checks if two shapes can be broadcast together
	CanBroadcast(shape1, shape2 []int) bool

	// BroadcastShapes determines the result shape of broadcasting two shapes
	BroadcastShapes(shape1, shape2 []int) ([]int, error)
}

BroadcastingOps defines broadcasting operations interface

type ComparisonOps

type ComparisonOps interface {
	// Equal performs element-wise equality comparison
	Equal(other *array.Array) (*array.Array, error)

	// NotEqual performs element-wise inequality comparison
	NotEqual(other *array.Array) (*array.Array, error)

	// Less performs element-wise less than comparison
	Less(other *array.Array) (*array.Array, error)

	// LessEqual performs element-wise less than or equal comparison
	LessEqual(other *array.Array) (*array.Array, error)

	// Greater performs element-wise greater than comparison
	Greater(other *array.Array) (*array.Array, error)

	// GreaterEqual performs element-wise greater than or equal comparison
	GreaterEqual(other *array.Array) (*array.Array, error)
}

ComparisonOps defines element-wise comparison operations interface

type EigenResult

type EigenResult struct {
	Values  *array.Array // Eigenvalues
	Vectors *array.Array // Eigenvectors (columns)
}

EigenResult represents the result of eigenvalue decomposition

func PowerMethod

func PowerMethod(arr *array.Array, maxIter int, tolerance float64) (*EigenResult, error)

PowerMethod computes the dominant eigenvalue and eigenvector using power iteration

type ILUPreconditioner

type ILUPreconditioner struct {
	L *array.Array // Lower triangular factor
	U *array.Array // Upper triangular factor
	// contains filtered or unexported fields
}

ILUPreconditioner implements Incomplete LU factorization preconditioning

func NewILUPreconditioner

func NewILUPreconditioner(A *array.Array, fillLevel int) (*ILUPreconditioner, error)

NewILUPreconditioner creates a new ILU preconditioner from matrix A The fillLevel parameter controls how much fill-in is allowed: - fillLevel = 0: ILU(0) - only original non-zero positions - fillLevel = 1: ILU(1) - allow one level of additional fill-in

func (*ILUPreconditioner) Apply

func (ilu *ILUPreconditioner) Apply(x *array.Array) (*array.Array, error)

Apply applies the ILU preconditioner to vector x Solves (LU)^(-1) * x by forward substitution (L * y = x) then backward substitution (U * result = y)

func (*ILUPreconditioner) GetDiagonal

func (ilu *ILUPreconditioner) GetDiagonal() *array.Array

GetDiagonal returns the diagonal of the U factor (not commonly used for ILU)

func (*ILUPreconditioner) GetL

func (ilu *ILUPreconditioner) GetL() *array.Array

GetL returns the L factor

func (*ILUPreconditioner) GetU

func (ilu *ILUPreconditioner) GetU() *array.Array

GetU returns the U factor

func (*ILUPreconditioner) Solve

func (ilu *ILUPreconditioner) Solve(x *array.Array) (*array.Array, error)

Solve solves M * y = x for y, which is equivalent to Apply for ILU preconditioners

type IterativeSolverOptions

type IterativeSolverOptions struct {
	MaxIterations int     // Maximum number of iterations (default: 1000)
	Tolerance     float64 // Convergence tolerance (default: 1e-6)
	Verbose       bool    // Print convergence information
}

IterativeSolverOptions contains options for iterative solvers

func DefaultIterativeSolverOptions

func DefaultIterativeSolverOptions() *IterativeSolverOptions

DefaultIterativeSolverOptions returns default solver options

type IterativeSolverResult

type IterativeSolverResult struct {
	Solution   *array.Array // Solution vector x
	Iterations int          // Number of iterations performed
	Residual   float64      // Final residual norm
	Converged  bool         // Whether the solver converged
	Error      error        // Any error encountered
}

IterativeSolverResult contains the results of iterative linear system solving

func BiCGSTAB

func BiCGSTAB(A, b *array.Array, options *IterativeSolverOptions) *IterativeSolverResult

BiCGSTAB solves the linear system Ax = b using the Bi-Conjugate Gradient Stabilized method This method is effective for general non-symmetric matrices

func ConjugateGradient

func ConjugateGradient(A, b *array.Array, options *IterativeSolverOptions) *IterativeSolverResult

ConjugateGradient solves the linear system Ax = b using the Conjugate Gradient method This method is efficient for symmetric positive-definite matrices

func GMRES

func GMRES(A, b *array.Array, restart int, options *IterativeSolverOptions) *IterativeSolverResult

GMRES solves the linear system Ax = b using the Generalized Minimal Residual method This method works for general (non-symmetric) matrices

func PreconditionedConjugateGradient

func PreconditionedConjugateGradient(A *array.Array, b *array.Array, preconditioner Preconditioner, options *IterativeSolverOptions) *IterativeSolverResult

PreconditionedConjugateGradient solves A*x = b using preconditioned conjugate gradient

type JacobiPreconditioner

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

JacobiPreconditioner implements Jacobi (diagonal) preconditioning

func NewJacobiPreconditioner

func NewJacobiPreconditioner(A *array.Array) (*JacobiPreconditioner, error)

NewJacobiPreconditioner creates a new Jacobi preconditioner from matrix A The Jacobi preconditioner is M = diag(A), where M^(-1) = diag(1/A[i,i])

func (*JacobiPreconditioner) Apply

func (jp *JacobiPreconditioner) Apply(x *array.Array) (*array.Array, error)

Apply applies the Jacobi preconditioner to vector x Result[i] = x[i] / A[i,i] (where A[i,i] are the original diagonal elements)

func (*JacobiPreconditioner) GetDiagonal

func (jp *JacobiPreconditioner) GetDiagonal() *array.Array

GetDiagonal returns the diagonal of the inverse preconditioning matrix

func (*JacobiPreconditioner) Solve

func (jp *JacobiPreconditioner) Solve(x *array.Array) (*array.Array, error)

Solve solves M * y = x for y, which is equivalent to Apply for diagonal preconditioners

type LUResult

type LUResult struct {
	L *array.Array // Lower triangular matrix
	U *array.Array // Upper triangular matrix
	P *array.Array // Permutation matrix
}

LUResult represents the result of LU decomposition

func LU

func LU(arr *array.Array) (*LUResult, error)

LU computes the LU decomposition of a square matrix A = P*L*U

type LinearAlgebraOps

type LinearAlgebraOps interface {
	// Dot performs matrix multiplication or dot product
	Dot(other *array.Array) (*array.Array, error)

	// MatMul performs matrix multiplication (same as Dot but stricter about dimensions)
	MatMul(other *array.Array) (*array.Array, error)

	// Cross computes cross product for 3D vectors
	Cross(other *array.Array) (*array.Array, error)

	// Norm computes vector or matrix norm
	Norm(ord interface{}, axis ...int) (*array.Array, error)
}

LinearAlgebraOps defines linear algebra operations interface

type MaskingOps

type MaskingOps interface {
	// Where returns elements chosen from x or y depending on condition
	Where(condition, x, y *array.Array) (*array.Array, error)

	// MaskedWhere applies mask and returns elements where condition is true
	MaskedWhere(condition *array.Array) (*array.Array, error)

	// Select returns elements chosen from choices based on conditions
	Select(condlist []*array.Array, choicelist []*array.Array, default_ interface{}) (*array.Array, error)

	// Clip limits values to specified range
	Clip(min, max interface{}) (*array.Array, error)
}

MaskingOps defines masking and conditional operations interface

type NaNHandlingOps

type NaNHandlingOps interface {
	// NaNSum computes sum, ignoring NaN values
	NaNSum(axis ...int) (*array.Array, error)

	// NaNMean computes mean, ignoring NaN values
	NaNMean(axis ...int) (*array.Array, error)

	// NaNMax finds maximum, ignoring NaN values
	NaNMax(axis ...int) (*array.Array, error)

	// NaNMin finds minimum, ignoring NaN values
	NaNMin(axis ...int) (*array.Array, error)

	// NaNStd computes standard deviation, ignoring NaN values
	NaNStd(axis ...int) (*array.Array, error)

	// NaNVar computes variance, ignoring NaN values
	NaNVar(axis ...int) (*array.Array, error)
}

NaNHandlingOps defines NaN-aware operations interface

type PCAResult

type PCAResult struct {
	Components             *array.Array // Principal components (eigenvectors)
	ExplainedVariance      *array.Array // Variance explained by each component
	ExplainedVarianceRatio *array.Array // Proportion of variance explained
	SingularValues         *array.Array // Singular values from SVD
	Mean                   *array.Array // Mean of original data (for centering)
}

PCAResult represents the result of Principal Component Analysis

func PCA

func PCA(data *array.Array, nComponents int) (*PCAResult, error)

PCA performs Principal Component Analysis using SVD data should be organized as samples x features

func (*PCAResult) InverseTransform

func (pca *PCAResult) InverseTransform(transformedData *array.Array) (*array.Array, error)

InverseTransform reconstructs data from principal component representation

func (*PCAResult) Transform

func (pca *PCAResult) Transform(data *array.Array) (*array.Array, error)

Transform projects data onto the principal components

type Polynomial

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

Polynomial represents a polynomial with floating-point coefficients Coefficients are stored in ascending order of powers: [c₀, c₁, c₂, ...] for c₀ + c₁x + c₂x² + ...

func NewPolynomial

func NewPolynomial(coefficients []float64) *Polynomial

NewPolynomial creates a new polynomial from coefficients Coefficients are in ascending order of powers: [constant, linear, quadratic, ...]

func PolynomialFit

func PolynomialFit(xData, yData *array.Array, degree int) (*Polynomial, error)

PolynomialFit performs polynomial fitting using least squares

func (*Polynomial) Add

func (p *Polynomial) Add(other *Polynomial) (*Polynomial, error)

Add adds two polynomials

func (*Polynomial) Coefficients

func (p *Polynomial) Coefficients() []float64

Coefficients returns a copy of the polynomial coefficients

func (*Polynomial) Compose

func (p *Polynomial) Compose(q *Polynomial) (*Polynomial, error)

Compose computes the composition p(q(x))

func (*Polynomial) Copy

func (p *Polynomial) Copy() *Polynomial

Copy creates a deep copy of the polynomial

func (*Polynomial) DefiniteIntegral

func (p *Polynomial) DefiniteIntegral(a, b float64) (float64, error)

DefiniteIntegral computes the definite integral from a to b

func (*Polynomial) Degree

func (p *Polynomial) Degree() int

Degree returns the degree of the polynomial

func (*Polynomial) Derivative

func (p *Polynomial) Derivative() *Polynomial

Derivative returns the derivative of the polynomial

func (*Polynomial) Divide

func (p *Polynomial) Divide(divisor *Polynomial) (*Polynomial, *Polynomial, error)

Divide performs polynomial long division

func (*Polynomial) Equal

func (p *Polynomial) Equal(other *Polynomial) bool

Equal checks if two polynomials are equal

func (*Polynomial) Evaluate

func (p *Polynomial) Evaluate(x float64) float64

Evaluate evaluates the polynomial at a given point using Horner's method

func (*Polynomial) EvaluateArray

func (p *Polynomial) EvaluateArray(xValues *array.Array) (*array.Array, error)

EvaluateArray evaluates the polynomial at multiple points

func (*Polynomial) FindRoots

func (p *Polynomial) FindRoots() ([]float64, error)

FindRoots finds the real roots of the polynomial

func (*Polynomial) GCD

func (p *Polynomial) GCD(other *Polynomial) (*Polynomial, error)

GCD computes the greatest common divisor of two polynomials using Euclidean algorithm

func (*Polynomial) Integral

func (p *Polynomial) Integral(constant float64) *Polynomial

Integral returns the integral of the polynomial with given constant of integration

func (*Polynomial) Multiply

func (p *Polynomial) Multiply(other *Polynomial) (*Polynomial, error)

Multiply multiplies two polynomials

func (*Polynomial) Scale

func (p *Polynomial) Scale(factor float64) *Polynomial

Scale multiplies the polynomial by a scalar

func (*Polynomial) String

func (p *Polynomial) String() string

String returns a string representation of the polynomial

func (*Polynomial) Subtract

func (p *Polynomial) Subtract(other *Polynomial) (*Polynomial, error)

Subtract subtracts another polynomial from this one

type Preconditioner

type Preconditioner interface {
	// Apply applies the preconditioner to a vector: result = M^(-1) * x
	Apply(x *array.Array) (*array.Array, error)

	// Solve solves M * y = x for y, where M is the preconditioning matrix
	Solve(x *array.Array) (*array.Array, error)

	// GetDiagonal returns the diagonal of the preconditioning matrix (if applicable)
	GetDiagonal() *array.Array
}

Preconditioner interface defines methods for matrix preconditioning

type QRResult

type QRResult struct {
	Q *array.Array // Orthogonal matrix
	R *array.Array // Upper triangular matrix
}

QRResult represents the result of QR decomposition

func QR

func QR(arr *array.Array) (*QRResult, error)

QR computes the QR decomposition of a matrix A = Q*R using Gram-Schmidt

type ReductionOps

type ReductionOps interface {
	// Sum computes sum along specified axes
	Sum(axis ...int) (*array.Array, error)

	// Mean computes arithmetic mean along specified axes
	Mean(axis ...int) (*array.Array, error)

	// Max finds maximum values along specified axes
	Max(axis ...int) (*array.Array, error)

	// Min finds minimum values along specified axes
	Min(axis ...int) (*array.Array, error)

	// Std computes standard deviation along specified axes
	Std(axis ...int) (*array.Array, error)

	// Var computes variance along specified axes
	Var(axis ...int) (*array.Array, error)

	// Prod computes product along specified axes
	Prod(axis ...int) (*array.Array, error)

	// ArgMax finds indices of maximum values along specified axes
	ArgMax(axis ...int) (*array.Array, error)

	// ArgMin finds indices of minimum values along specified axes
	ArgMin(axis ...int) (*array.Array, error)

	// All tests whether all elements evaluate to True along specified axes
	All(axis ...int) (*array.Array, error)

	// Any tests whether any element evaluates to True along specified axes
	Any(axis ...int) (*array.Array, error)
}

ReductionOps defines reduction operations interface

type SSORPreconditioner

type SSORPreconditioner struct {
	D *array.Array // Diagonal part of A
	L *array.Array // Strictly lower triangular part of A
	U *array.Array // Strictly upper triangular part of A
	// contains filtered or unexported fields
}

SSORPreconditioner implements Symmetric Successive Over-Relaxation preconditioning SSOR is particularly effective for symmetric positive definite matrices

func NewSSORPreconditioner

func NewSSORPreconditioner(A *array.Array, omega float64) (*SSORPreconditioner, error)

NewSSORPreconditioner creates a new SSOR preconditioner from matrix A The omega parameter is the relaxation parameter: - omega = 1.0: Gauss-Seidel method - omega < 1.0: Under-relaxation (more stable) - omega > 1.0: Over-relaxation (faster convergence if stable) - Theoretical optimal range: 0 < omega < 2

func (*SSORPreconditioner) Apply

func (ssor *SSORPreconditioner) Apply(x *array.Array) (*array.Array, error)

Apply applies the SSOR preconditioner to vector x SSOR preconditioning involves two sweeps: 1. Forward sweep: (D + ωL) * y = ω * x 2. Backward sweep: (D + ωU) * result = D * y The complete SSOR preconditioner is M = (1/ω)(D + ωL)D^(-1)(D + ωU)

func (*SSORPreconditioner) GetComponents

func (ssor *SSORPreconditioner) GetComponents() (*array.Array, *array.Array, *array.Array)

GetComponents returns the D, L, U components (for debugging/analysis)

func (*SSORPreconditioner) GetDiagonal

func (ssor *SSORPreconditioner) GetDiagonal() *array.Array

GetDiagonal returns the inverse of the diagonal elements (for consistency with other preconditioners)

func (*SSORPreconditioner) GetOmega

func (ssor *SSORPreconditioner) GetOmega() float64

GetOmega returns the relaxation parameter

func (*SSORPreconditioner) Solve

func (ssor *SSORPreconditioner) Solve(x *array.Array) (*array.Array, error)

Solve solves M * z = x for z, which is equivalent to Apply for SSOR preconditioners

type SVDResult

type SVDResult struct {
	U *array.Array // Left singular vectors
	S *array.Array // Singular values
	V *array.Array // Right singular vectors (V^T)
}

SVDResult represents the result of Singular Value Decomposition

func SVD

func SVD(arr *array.Array) (*SVDResult, error)

SVD computes the Singular Value Decomposition A = U * S * V^T Uses the Jacobi SVD method which is stable for small to medium matrices

type ScalarOps

type ScalarOps interface {
	// AddScalar adds a scalar value to all elements
	AddScalar(scalar interface{}) (*array.Array, error)

	// SubScalar subtracts a scalar value from all elements
	SubScalar(scalar interface{}) (*array.Array, error)

	// MulScalar multiplies all elements by a scalar value
	MulScalar(scalar interface{}) (*array.Array, error)

	// DivScalar divides all elements by a scalar value
	DivScalar(scalar interface{}) (*array.Array, error)

	// PowScalar raises all elements to a scalar power
	PowScalar(scalar interface{}) (*array.Array, error)
}

ScalarOps defines operations with scalar values interface

type SortingOps

type SortingOps interface {
	// Sort returns sorted copy of array
	Sort(axis int) (*array.Array, error)

	// ArgSort returns indices that would sort the array
	ArgSort(axis int) (*array.Array, error)

	// SearchSorted finds indices where elements should be inserted to maintain order
	SearchSorted(values *array.Array, side string) (*array.Array, error)

	// Unique finds unique elements of array
	Unique() (*array.Array, *array.Array, *array.Array, error) // values, indices, inverse, counts

	// Partition partitions array elements
	Partition(kth int, axis int) (*array.Array, error)
}

SortingOps defines sorting and searching operations interface

type StatisticalOps

type StatisticalOps interface {
	// Median computes median along specified axes
	Median(axis ...int) (*array.Array, error)

	// Percentile computes percentile along specified axes
	Percentile(q float64, axis ...int) (*array.Array, error)

	// Quantile computes quantile along specified axes
	Quantile(q float64, axis ...int) (*array.Array, error)

	// Histogram computes histogram of array values
	Histogram(bins int) (values *array.Array, binEdges *array.Array, err error)

	// Corrcoef computes correlation coefficient matrix
	Corrcoef() (*array.Array, error)

	// Cov computes covariance matrix
	Cov() (*array.Array, error)
}

StatisticalOps defines statistical operations interface

type UnaryFunc

type UnaryFunc func(x interface{}) interface{}

UnaryFunc represents a universal function that operates on a single array

type UniversalFunc

type UniversalFunc interface {
	// Trigonometric functions
	Sin() *array.Array
	Cos() *array.Array
	Tan() *array.Array
	Asin() *array.Array
	Acos() *array.Array
	Atan() *array.Array

	// Hyperbolic functions
	Sinh() *array.Array
	Cosh() *array.Array
	Tanh() *array.Array

	// Exponential and logarithmic functions
	Exp() *array.Array
	Exp2() *array.Array
	Log() *array.Array
	Log2() *array.Array
	Log10() *array.Array

	// Power and root functions
	Sqrt() *array.Array
	Cbrt() *array.Array
	Square() *array.Array

	// Rounding functions
	Ceil() *array.Array
	Floor() *array.Array
	Round() *array.Array
	Trunc() *array.Array

	// Sign and absolute functions
	Abs() *array.Array
	Sign() *array.Array

	// Special functions
	IsNaN() *array.Array
	IsInf() *array.Array
	IsFinite() *array.Array
}

UniversalFunc defines universal mathematical functions interface

Jump to

Keyboard shortcuts

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