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 ¶
- func Abs(arr *array.Array) (*array.Array, error)
- func AbsInPlace(arr *array.Array) error
- func Acos(arr *array.Array) (*array.Array, error)
- func AcosInPlace(arr *array.Array) error
- func Acosh(arr *array.Array) (*array.Array, error)
- func AcoshInPlace(arr *array.Array) error
- func ApplyBinary(a, b *array.Array, fn BinaryFunc) (*array.Array, error)
- func ApplyUnary(arr *array.Array, fn UnaryFunc) (*array.Array, error)
- func ApplyUnaryInPlace(arr *array.Array, fn UnaryFunc) error
- func Asin(arr *array.Array) (*array.Array, error)
- func AsinInPlace(arr *array.Array) error
- func Asinh(arr *array.Array) (*array.Array, error)
- func AsinhInPlace(arr *array.Array) error
- func Atan(arr *array.Array) (*array.Array, error)
- func Atan2(y, x *array.Array) (*array.Array, error)
- func AtanInPlace(arr *array.Array) error
- func Atanh(arr *array.Array) (*array.Array, error)
- func AtanhInPlace(arr *array.Array) error
- func Cbrt(arr *array.Array) (*array.Array, error)
- func CbrtInPlace(arr *array.Array) error
- func Ceil(arr *array.Array) (*array.Array, error)
- func CeilInPlace(arr *array.Array) error
- func Chol(arr *array.Array) (*array.Array, error)
- func Clip(arr *array.Array, min, max float64) (*array.Array, error)
- func ClipInPlace(arr *array.Array, min, max float64) error
- func CompensatedDotProduct(a, b *array.Array) (float64, error)
- func CompensatedNorm(a *array.Array) (float64, error)
- func ConditionNumber(arr *array.Array) (float64, error)
- func Copysign(x, y *array.Array) (*array.Array, error)
- func Cos(arr *array.Array) (*array.Array, error)
- func CosInPlace(arr *array.Array) error
- func Cosh(arr *array.Array) (*array.Array, error)
- func CoshInPlace(arr *array.Array) error
- func Deg2Rad(arr *array.Array) (*array.Array, error)
- func Deg2RadInPlace(arr *array.Array) error
- func Det(arr *array.Array) (float64, error)
- func Dot(a, b *array.Array) (*array.Array, error)
- func Exp(arr *array.Array) (*array.Array, error)
- func Exp2(arr *array.Array) (*array.Array, error)
- func Exp2InPlace(arr *array.Array) error
- func Exp10(arr *array.Array) (*array.Array, error)
- func Exp10InPlace(arr *array.Array) error
- func ExpInPlace(arr *array.Array) error
- func Expm1(arr *array.Array) (*array.Array, error)
- func Expm1InPlace(arr *array.Array) error
- func ExtendedPrecisionSum(a *array.Array) (float64, error)
- func Fix(arr *array.Array) (*array.Array, error)
- func FixInPlace(arr *array.Array) error
- func Floor(arr *array.Array) (*array.Array, error)
- func FloorInPlace(arr *array.Array) error
- func Fmod(x, y *array.Array) (*array.Array, error)
- func Hypot(x, y *array.Array) (*array.Array, error)
- func KahanMean(a *array.Array) (float64, error)
- func KahanStandardDeviation(a *array.Array, ddof int) (float64, error)
- func KahanSum(a *array.Array) (float64, error)
- func KahanVariance(a *array.Array, ddof int) (float64, error)
- func Log(arr *array.Array) (*array.Array, error)
- func Log1p(arr *array.Array) (*array.Array, error)
- func Log1pInPlace(arr *array.Array) error
- func Log2(arr *array.Array) (*array.Array, error)
- func Log2InPlace(arr *array.Array) error
- func Log10(arr *array.Array) (*array.Array, error)
- func Log10InPlace(arr *array.Array) error
- func LogInPlace(arr *array.Array) error
- func Logb(arr *array.Array) (*array.Array, error)
- func LogbInPlace(arr *array.Array) error
- func MatMul(a, b *array.Array) (*array.Array, error)
- func Maximum(a, b *array.Array) (*array.Array, error)
- func Minimum(a, b *array.Array) (*array.Array, error)
- func NeumaierSum(a *array.Array) (float64, error)
- func Norm(arr *array.Array, ord interface{}) (float64, error)
- func PairwiseSum(a *array.Array) (float64, error)
- func Power(x, y *array.Array) (*array.Array, error)
- func PowerScalar(arr *array.Array, scalar float64) (*array.Array, error)
- func PowerScalarInPlace(arr *array.Array, scalar float64) error
- func Rad2Deg(arr *array.Array) (*array.Array, error)
- func Rad2DegInPlace(arr *array.Array) error
- func Rank(arr *array.Array, tolerance float64) (int, error)
- func Reciprocal(arr *array.Array) (*array.Array, error)
- func ReciprocalInPlace(arr *array.Array) error
- func Remainder(x, y *array.Array) (*array.Array, error)
- func Rint(arr *array.Array) (*array.Array, error)
- func RintInPlace(arr *array.Array) error
- func Round(arr *array.Array) (*array.Array, error)
- func RoundInPlace(arr *array.Array) error
- func RoundN(arr *array.Array, n int) (*array.Array, error)
- func RoundNInPlace(arr *array.Array, n int) error
- func Sign(arr *array.Array) (*array.Array, error)
- func SignInPlace(arr *array.Array) error
- func Sin(arr *array.Array) (*array.Array, error)
- func SinInPlace(arr *array.Array) error
- func Sinh(arr *array.Array) (*array.Array, error)
- func SinhInPlace(arr *array.Array) error
- func Solve(A, b *array.Array) (*array.Array, error)
- func Sqrt(arr *array.Array) (*array.Array, error)
- func SqrtInPlace(arr *array.Array) error
- func Square(arr *array.Array) (*array.Array, error)
- func SquareInPlace(arr *array.Array) error
- func Tan(arr *array.Array) (*array.Array, error)
- func TanInPlace(arr *array.Array) error
- func Tanh(arr *array.Array) (*array.Array, error)
- func TanhInPlace(arr *array.Array) error
- func Trace(arr *array.Array) (interface{}, error)
- func Transpose(arr *array.Array) (*array.Array, error)
- func Trunc(arr *array.Array) (*array.Array, error)
- func TruncInPlace(arr *array.Array) error
- type ArithmeticOps
- type ArrayManipulationOps
- type BinaryFunc
- type BroadcastingOps
- type ComparisonOps
- type EigenResult
- type ILUPreconditioner
- func (ilu *ILUPreconditioner) Apply(x *array.Array) (*array.Array, error)
- func (ilu *ILUPreconditioner) GetDiagonal() *array.Array
- func (ilu *ILUPreconditioner) GetL() *array.Array
- func (ilu *ILUPreconditioner) GetU() *array.Array
- func (ilu *ILUPreconditioner) Solve(x *array.Array) (*array.Array, error)
- type IterativeSolverOptions
- type IterativeSolverResult
- func BiCGSTAB(A, b *array.Array, options *IterativeSolverOptions) *IterativeSolverResult
- func ConjugateGradient(A, b *array.Array, options *IterativeSolverOptions) *IterativeSolverResult
- func GMRES(A, b *array.Array, restart int, options *IterativeSolverOptions) *IterativeSolverResult
- func PreconditionedConjugateGradient(A *array.Array, b *array.Array, preconditioner Preconditioner, ...) *IterativeSolverResult
- type JacobiPreconditioner
- type LUResult
- type LinearAlgebraOps
- type MaskingOps
- type NaNHandlingOps
- type PCAResult
- type Polynomial
- func (p *Polynomial) Add(other *Polynomial) (*Polynomial, error)
- func (p *Polynomial) Coefficients() []float64
- func (p *Polynomial) Compose(q *Polynomial) (*Polynomial, error)
- func (p *Polynomial) Copy() *Polynomial
- func (p *Polynomial) DefiniteIntegral(a, b float64) (float64, error)
- func (p *Polynomial) Degree() int
- func (p *Polynomial) Derivative() *Polynomial
- func (p *Polynomial) Divide(divisor *Polynomial) (*Polynomial, *Polynomial, error)
- func (p *Polynomial) Equal(other *Polynomial) bool
- func (p *Polynomial) Evaluate(x float64) float64
- func (p *Polynomial) EvaluateArray(xValues *array.Array) (*array.Array, error)
- func (p *Polynomial) FindRoots() ([]float64, error)
- func (p *Polynomial) GCD(other *Polynomial) (*Polynomial, error)
- func (p *Polynomial) Integral(constant float64) *Polynomial
- func (p *Polynomial) Multiply(other *Polynomial) (*Polynomial, error)
- func (p *Polynomial) Scale(factor float64) *Polynomial
- func (p *Polynomial) String() string
- func (p *Polynomial) Subtract(other *Polynomial) (*Polynomial, error)
- type Preconditioner
- type QRResult
- type ReductionOps
- type SSORPreconditioner
- func (ssor *SSORPreconditioner) Apply(x *array.Array) (*array.Array, error)
- func (ssor *SSORPreconditioner) GetComponents() (*array.Array, *array.Array, *array.Array)
- func (ssor *SSORPreconditioner) GetDiagonal() *array.Array
- func (ssor *SSORPreconditioner) GetOmega() float64
- func (ssor *SSORPreconditioner) Solve(x *array.Array) (*array.Array, error)
- type SVDResult
- type ScalarOps
- type SortingOps
- type StatisticalOps
- type UnaryFunc
- type UniversalFunc
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AbsInPlace ¶
AbsInPlace computes the absolute value of array elements in-place
func AcosInPlace ¶
AcosInPlace computes the arccosine of array elements in-place
func AcoshInPlace ¶
AcoshInPlace computes the inverse hyperbolic cosine of array elements in-place
func ApplyBinary ¶
ApplyBinary applies a binary universal function to two arrays with broadcasting
func ApplyUnary ¶
ApplyUnary applies a unary universal function to an array
func ApplyUnaryInPlace ¶
ApplyUnaryInPlace applies a unary universal function to an array in-place
func AsinInPlace ¶
AsinInPlace computes the arcsine of array elements in-place
func AsinhInPlace ¶
AsinhInPlace computes the inverse hyperbolic sine of array elements in-place
func Atan2 ¶
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 ¶
AtanInPlace computes the arctangent of array elements in-place
func AtanhInPlace ¶
AtanhInPlace computes the inverse hyperbolic tangent of array elements in-place
func CbrtInPlace ¶
CbrtInPlace computes the cube root of array elements in-place
func CeilInPlace ¶
CeilInPlace returns the ceiling of array elements in-place
func ClipInPlace ¶
ClipInPlace clips array values to be within [min, max] range in-place
func CompensatedDotProduct ¶
CompensatedDotProduct computes dot product with Kahan summation for better precision
func CompensatedNorm ¶
CompensatedNorm computes the L2 norm with enhanced numerical stability
func ConditionNumber ¶
ConditionNumber computes the condition number of a matrix using SVD Returns the ratio of largest to smallest singular value
func CosInPlace ¶
CosInPlace computes the cosine of array elements in-place
func CoshInPlace ¶
CoshInPlace computes the hyperbolic cosine of array elements in-place
func Deg2RadInPlace ¶
Deg2RadInPlace converts degrees to radians in-place
func Dot ¶
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 Exp2InPlace ¶
Exp2InPlace computes 2^x for array elements in-place
func Exp10InPlace ¶
Exp10InPlace computes 10^x for array elements in-place
func ExpInPlace ¶
ExpInPlace computes the exponential of array elements in-place
func Expm1InPlace ¶
Expm1InPlace computes exp(x) - 1 for array elements in-place
func ExtendedPrecisionSum ¶
ExtendedPrecisionSum uses extended precision arithmetic for critical summations This uses a form of double-double arithmetic for even better precision
func FixInPlace ¶
FixInPlace rounds array elements towards zero in-place
func FloorInPlace ¶
FloorInPlace returns the floor of array elements in-place
func KahanStandardDeviation ¶
KahanStandardDeviation computes standard deviation using Kahan-based variance
func KahanSum ¶
KahanSum performs Kahan summation algorithm on an array This provides much better numerical stability than naive summation for large arrays
func KahanVariance ¶
KahanVariance computes variance using Kahan summation for numerical stability Uses the two-pass algorithm with compensated summation
func Log1pInPlace ¶
Log1pInPlace computes log(1 + x) for array elements in-place
func Log2InPlace ¶
Log2InPlace computes the base-2 logarithm of array elements in-place
func Log10InPlace ¶
Log10InPlace computes the base-10 logarithm of array elements in-place
func LogInPlace ¶
LogInPlace computes the natural logarithm of array elements in-place
func LogbInPlace ¶
LogbInPlace computes the binary logarithm of array elements in-place
func NeumaierSum ¶
NeumaierSum implements Neumaier's improved Kahan summation algorithm This is even more accurate than standard Kahan summation for certain cases
func PairwiseSum ¶
PairwiseSum implements pairwise summation for improved numerical stability This algorithm has O(log n) error accumulation instead of O(n) for naive summation
func PowerScalar ¶
PowerScalar computes x^scalar for array elements
func PowerScalarInPlace ¶
PowerScalarInPlace computes x^scalar for array elements in-place
func Rad2DegInPlace ¶
Rad2DegInPlace converts radians to degrees in-place
func Reciprocal ¶
Reciprocal computes 1/x for array elements
func ReciprocalInPlace ¶
ReciprocalInPlace computes 1/x for array elements in-place
func RintInPlace ¶
RintInPlace rounds array elements to nearest integer in-place
func RoundInPlace ¶
RoundInPlace rounds array elements to the nearest integer in-place
func RoundNInPlace ¶
RoundNInPlace rounds array elements to n decimal places in-place
func SignInPlace ¶
SignInPlace returns the sign of array elements in-place
func Sin ¶
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 ¶
SinInPlace computes the sine of array elements in-place
func SinhInPlace ¶
SinhInPlace computes the hyperbolic sine of array elements in-place
func SqrtInPlace ¶
SqrtInPlace computes the square root of array elements in-place
func SquareInPlace ¶
SquareInPlace computes the square of array elements in-place
func TanInPlace ¶
TanInPlace computes the tangent of array elements in-place
func TanhInPlace ¶
TanhInPlace computes the hyperbolic tangent of array elements in-place
func Transpose ¶
Transpose returns the transpose of a 2-D array or swaps the last two axes for higher dimensions
func TruncInPlace ¶
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 ¶
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 ¶
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
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 ¶
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
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
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 ¶
PCA performs Principal Component Analysis using SVD data should be organized as samples x features
func (*PCAResult) InverseTransform ¶
InverseTransform reconstructs data from principal component representation
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 ¶
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
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 ¶
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 ¶
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
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
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