import { F as FactoryFunction$1 } from './index-B4LIOfHN.js'; export { U as Unit, a as UnitInstance, i as isUnitValue } from './index-B4LIOfHN.js'; import { TypedInstance, ReferTo, ReferToSelf, TypedFunction, SignatureFunction } from 'typed-function'; export { ReferTo, ReferToSelf, SignatureFunction, TypedFunction, TypedInstance, create, default as typed } from 'typed-function'; /** * Base interfaces for MathTS types * @module @danielsimonjr/mathts-core/types/interfaces */ /** * Base interface for all MathTS numeric types */ interface MathTSValue { readonly type: string; valueOf(): number | bigint; toString(): string; toJSON(): unknown; } /** * Scalar types that support arithmetic */ interface Scalar extends MathTSValue { add(other: Scalar): Scalar; subtract(other: Scalar): Scalar; multiply(other: Scalar): Scalar; divide(other: Scalar): Scalar; negate(): Scalar; abs(): Scalar | number; } /** * Available computation backends */ type BackendType = 'js' | 'wasm' | 'gpu'; /** * Supported numeric types */ type NumericType = 'float32' | 'float64' | 'int32' | 'int64' | 'complex64' | 'complex128'; /** * Matrix backend interface */ interface MatrixBackend { readonly name: BackendType; readonly isAvailable: boolean; matmul(a: Float64Array, b: Float64Array, m: number, n: number, k: number): Float64Array; transpose(data: Float64Array, rows: number, cols: number): Float64Array; add(a: Float64Array, b: Float64Array): Float64Array; subtract(a: Float64Array, b: Float64Array): Float64Array; scale(data: Float64Array, scalar: number): Float64Array; lu(data: Float64Array, n: number): { L: Float64Array; U: Float64Array; P: Int32Array; }; qr(data: Float64Array, m: number, n: number): { Q: Float64Array; R: Float64Array; }; svd(data: Float64Array, m: number, n: number): { U: Float64Array; S: Float64Array; V: Float64Array; }; eig(data: Float64Array, n: number): { values: Float64Array; vectors: Float64Array; }; } /** * Matrix interface with backend abstraction */ interface IMatrix extends MathTSValue { readonly rows: number; readonly cols: number; readonly size: readonly [number, number]; readonly length: number; readonly backend: MatrixBackend; get(row: number, col: number): T; set(row: number, col: number, value: T): void; row(index: number): IMatrix; column(index: number): IMatrix; slice(rowStart: number, rowEnd: number, colStart: number, colEnd: number): IMatrix; transpose(): IMatrix; reshape(rows: number, cols: number): IMatrix; flatten(): T[]; add(other: IMatrix | T): IMatrix; subtract(other: IMatrix | T): IMatrix; multiply(other: IMatrix | T): IMatrix; toArray(): T[][]; toBuffer(): ArrayBuffer; clone(): IMatrix; } /** * Complex number interface */ interface IComplex extends Scalar { readonly re: number; readonly im: number; conjugate(): IComplex; arg(): number; sqrt(): IComplex; exp(): IComplex; log(): IComplex; } /** * Fraction interface for exact rational arithmetic */ interface IFraction extends Scalar { readonly numerator: bigint; readonly denominator: bigint; simplify(): IFraction; toNumber(): number; } /** * BigNumber interface for arbitrary precision decimals */ interface IBigNumber extends MathTSValue { add(other: IBigNumber | number | string): IBigNumber; subtract(other: IBigNumber | number | string): IBigNumber; multiply(other: IBigNumber | number | string): IBigNumber; divide(other: IBigNumber | number | string): IBigNumber; negate(): IBigNumber; abs(): IBigNumber; pow(n: number | bigint): IBigNumber; sqrt(): IBigNumber; isNaN(): boolean; isFinite(): boolean; isInfinite(): boolean; isZero(): boolean; isPositive(): boolean; isNegative(): boolean; isInteger(): boolean; equals(other: IBigNumber): boolean; lessThan(other: IBigNumber): boolean; greaterThan(other: IBigNumber): boolean; compareTo(other: IBigNumber): number; toFixed(decimalPlaces?: number): string; toExponential(decimalPlaces?: number): string; toPrecision(significantDigits?: number): string; toBigInt(): bigint; } /** * Matrix dimensions */ interface MatrixDimensions { rows: number; cols: number; } /** * Complex number implementation * @module @danielsimonjr/mathts-core/types/complex */ /** * Check if a value is a Complex number */ declare function isComplex(value: unknown): value is Complex; /** * Complex number class with full arithmetic support * Implements the IComplex interface for type-safe complex number operations. */ declare class Complex implements IComplex { readonly type = "Complex"; readonly re: number; readonly im: number; constructor(re: number, im?: number); /** * Create a Complex from polar form (r, θ) * @param r - magnitude (radius) * @param theta - angle in radians */ static fromPolar(r: number, theta: number): Complex; /** * Create a Complex from a real number */ static fromNumber(n: number): Complex; /** * Create a Complex from a JSON object */ static fromJSON(json: { re: number; im: number; }): Complex; /** * Parse a complex number from a string * Supports formats: "3+4i", "3-4i", "3", "4i", "-4i", "i", "-i" */ static parse(str: string): Complex; /** * Compare two complex numbers lexicographically (re first, then im) * @returns -1, 0, or 1 */ static compare(a: Complex, b: Complex): number; valueOf(): number; toString(): string; toJSON(): { mathjs: string; re: number; im: number; }; /** * Return polar representation */ toPolar(): { r: number; phi: number; }; /** * Format with options (precision, notation, etc.) */ format(options?: { precision?: number; notation?: 'fixed' | 'exponential' | 'auto'; }): string; /** * Complex conjugate (a + bi → a - bi) */ conjugate(): Complex; /** * Magnitude (absolute value) |z| = √(re² + im²) */ abs(): number; /** * Phase angle (argument) in radians, range (-π, π] */ arg(): number; /** * Squared magnitude |z|² = re² + im² * More efficient than abs() when you don't need the square root */ abs2(): number; /** * Addition: (a + bi) + (c + di) = (a + c) + (b + d)i */ add(other: Scalar): Complex; /** * Subtraction: (a + bi) - (c + di) = (a - c) + (b - d)i */ subtract(other: Scalar): Complex; /** * Multiplication: (a + bi)(c + di) = (ac - bd) + (ad + bc)i */ multiply(other: Scalar): Complex; /** * Division: (a + bi)/(c + di) = ((ac + bd) + (bc - ad)i) / (c² + d²) */ divide(other: Scalar): Complex; sub(other: Scalar): Complex; mul(other: Scalar): Complex; div(other: Scalar): Complex; neg(): Complex; /** * Negation: -(a + bi) = -a - bi */ negate(): Complex; /** * Multiplicative inverse: 1/z = z̄/|z|² */ inverse(): Complex; /** * Square root using principal branch * √z = √r · e^(iθ/2) where r = |z|, θ = arg(z) */ sqrt(): Complex; /** * n-th root (returns principal root) */ nthRoot(n: number): Complex; /** * All n-th roots */ nthRoots(n: number): Complex[]; /** * Exponential: e^(a+bi) = e^a · (cos(b) + i·sin(b)) */ exp(): Complex; /** * Natural logarithm: ln(z) = ln|z| + i·arg(z) */ log(): Complex; /** * Logarithm base 10 */ log10(): Complex; /** * Logarithm base 2 */ log2(): Complex; /** * Power: z^w = e^(w·ln(z)) */ pow(n: number | Complex): Complex; /** * Sine: sin(a + bi) = sin(a)cosh(b) + i·cos(a)sinh(b) */ sin(): Complex; /** * Cosine: cos(a + bi) = cos(a)cosh(b) - i·sin(a)sinh(b) */ cos(): Complex; /** * Tangent: tan(z) = sin(z) / cos(z) */ tan(): Complex; /** * Cotangent: cot(z) = cos(z) / sin(z) */ cot(): Complex; /** * Secant: sec(z) = 1 / cos(z) */ sec(): Complex; /** * Cosecant: csc(z) = 1 / sin(z) */ csc(): Complex; /** * Hyperbolic sine: sinh(z) = (e^z - e^(-z)) / 2 */ sinh(): Complex; /** * Hyperbolic cosine: cosh(z) = (e^z + e^(-z)) / 2 */ cosh(): Complex; /** * Hyperbolic tangent: tanh(z) = sinh(z) / cosh(z) */ tanh(): Complex; /** * Hyperbolic cotangent: coth(z) = cosh(z) / sinh(z) */ coth(): Complex; /** * Hyperbolic secant: sech(z) = 1 / cosh(z) */ sech(): Complex; /** * Hyperbolic cosecant: csch(z) = 1 / sinh(z) */ csch(): Complex; /** * Arc sine: asin(z) = -i·ln(iz + √(1 - z²)) */ asin(): Complex; /** * Arc cosine: acos(z) = π/2 - asin(z) */ acos(): Complex; /** * Arc tangent: atan(z) = (i/2)·ln((i + z)/(i - z)) */ atan(): Complex; /** * Inverse hyperbolic sine: asinh(z) = ln(z + √(z² + 1)) */ asinh(): Complex; /** * Inverse hyperbolic cosine: acosh(z) = ln(z + √(z-1)·√(z+1)) * * The principal value has non-negative real part (C99 Annex G / DLMF 4.37 / * NumPy convention). Using the factored `√(z-1)·√(z+1)` rather than `√(z²-1)` * selects the correct Riemann sheet for Re(z) < 0 and on the real-axis branch * cuts (z < 1), where `√(z²-1)` lands on the wrong branch — the previous form * returned a negative real part (e.g. acosh(-1+0.5i)) and the wrong sign of π * on z < -1. */ acosh(): Complex; /** * Inverse hyperbolic tangent: atanh(z) = (1/2)·ln((1 + z)/(1 - z)) */ atanh(): Complex; /** * Check equality within tolerance */ equals(other: Complex, epsilon?: number): boolean; /** * Check if this is a real number (im ≈ 0) */ isReal(epsilon?: number): boolean; /** * Check if this is purely imaginary (re ≈ 0, im ≠ 0) */ isImaginary(epsilon?: number): boolean; /** * Check if this is zero */ isZero(epsilon?: number): boolean; /** * Check if this is NaN */ isNaN(): boolean; /** * Check if this is infinite */ isInfinite(): boolean; /** * Clone this complex number */ clone(): Complex; /** * Round real and imaginary parts to specified decimals */ round(decimals?: number): Complex; /** * Floor real and imaginary parts */ floor(): Complex; /** * Ceil real and imaginary parts */ ceil(): Complex; /** * Sign function: z / |z| (unit complex number in same direction) */ sign(): Complex; } /** * Imaginary unit constant: i = √(-1) */ declare const I: Complex; /** * Common constants */ declare const COMPLEX_ZERO: Complex; declare const COMPLEX_ONE: Complex; declare const COMPLEX_NEG_ONE: Complex; interface BigNumber$1 { toNumber(): number; } /** * Callback function for Range forEach operations */ type RangeForEachCallback = (value: number, index: number[], range: unknown) => void; /** * Callback function for Range map operations */ type RangeMapCallback = (value: number, index: number[], range: unknown) => T; /** * Formatting options for Range display */ interface RangeFormatOptions { precision?: number; notation?: 'fixed' | 'exponential' | 'engineering' | 'auto'; [key: string]: unknown; } /** * JSON representation of a Range */ interface RangeJSON { mathjs: 'Range'; start: number; end: number; step: number; } declare const createRangeClass: FactoryFunction$1<{ new (start?: number | bigint | BigNumber$1 | null, end?: number | bigint | BigNumber$1 | null, step?: number | bigint | BigNumber$1 | null): { /** * Type identifier */ readonly type: string; /** * Range type flag */ readonly isRange: boolean; /** * Start value of the range (inclusive) */ start: number; /** * End value of the range (exclusive) */ end: number; /** * Step size for the range */ step: number; /** * Cached primitive array representation */ "__#private@#cache": number[] | null; "__#private@#cacheStart"?: number; "__#private@#cacheEnd"?: number; "__#private@#cacheStep"?: number; /** * Create a clone of the range * @return {Range} clone */ clone(): /*elided*/ any; /** * Retrieve the size of the range. * Returns an array containing one number, the number of elements in the range. * @memberof Range * @returns {number[]} size */ size(): number[]; /** * Calculate the minimum value in the range * @memberof Range * @return {number | undefined} min */ min(): number | undefined; /** * Calculate the maximum value in the range * @memberof Range * @return {number | undefined} max */ max(): number | undefined; /** * Execute a callback function for each value in the range. * @memberof Range * @param {function} callback The callback method is invoked with three * parameters: the value of the element, the index * of the element, and the Range being traversed. */ forEach(callback: RangeForEachCallback): void; /** * Execute a callback function for each value in the Range, and return the * results as an array * @memberof Range * @param {function} callback The callback method is invoked with three * parameters: the value of the element, the index * of the element, and the Matrix being traversed. * @returns {Array} array */ map(callback: RangeMapCallback): T[]; /** * Create an Array with a copy of the Ranges data * @memberof Range * @returns {Array} array */ toArray(): number[]; /** * Get the primitive value of the Range, a one dimensional array * @memberof Range * @returns {Array} array */ valueOf(): number[]; /** * Get a string representation of the range, with optional formatting options. * Output is formatted as 'start:step:end', for example '2:6' or '0:0.2:11' * @memberof Range * @param {Object | number | function} [options] Formatting options. See * lib/utils/number:format for a * description of the available * options. * @returns {string} str */ format(options?: RangeFormatOptions | number | ((value: number) => string)): string; /** * Get a string representation of the range. * @memberof Range * @returns {string} */ toString(): string; /** * Get a JSON representation of the range * @memberof Range * @returns {Object} Returns a JSON object structured as: * `{"mathjs": "Range", "start": 2, "end": 4, "step": 1}` */ toJSON(): RangeJSON; }; /** * Parse a string into a range, * The string contains the start, optional step, and end, separated by a colon. * If the string does not contain a valid range, null is returned. * For example str='0:2:11'. * @memberof Range * @param {string} str * @return {Range | null} range */ parse(str: string): { /** * Type identifier */ readonly type: string; /** * Range type flag */ readonly isRange: boolean; /** * Start value of the range (inclusive) */ start: number; /** * End value of the range (exclusive) */ end: number; /** * Step size for the range */ step: number; /** * Cached primitive array representation */ "__#private@#cache": number[] | null; "__#private@#cacheStart"?: number; "__#private@#cacheEnd"?: number; "__#private@#cacheStep"?: number; /** * Create a clone of the range * @return {Range} clone */ clone(): /*elided*/ any; /** * Retrieve the size of the range. * Returns an array containing one number, the number of elements in the range. * @memberof Range * @returns {number[]} size */ size(): number[]; /** * Calculate the minimum value in the range * @memberof Range * @return {number | undefined} min */ min(): number | undefined; /** * Calculate the maximum value in the range * @memberof Range * @return {number | undefined} max */ max(): number | undefined; /** * Execute a callback function for each value in the range. * @memberof Range * @param {function} callback The callback method is invoked with three * parameters: the value of the element, the index * of the element, and the Range being traversed. */ forEach(callback: RangeForEachCallback): void; /** * Execute a callback function for each value in the Range, and return the * results as an array * @memberof Range * @param {function} callback The callback method is invoked with three * parameters: the value of the element, the index * of the element, and the Matrix being traversed. * @returns {Array} array */ map(callback: RangeMapCallback): T[]; /** * Create an Array with a copy of the Ranges data * @memberof Range * @returns {Array} array */ toArray(): number[]; /** * Get the primitive value of the Range, a one dimensional array * @memberof Range * @returns {Array} array */ valueOf(): number[]; /** * Get a string representation of the range, with optional formatting options. * Output is formatted as 'start:step:end', for example '2:6' or '0:0.2:11' * @memberof Range * @param {Object | number | function} [options] Formatting options. See * lib/utils/number:format for a * description of the available * options. * @returns {string} str */ format(options?: RangeFormatOptions | number | ((value: number) => string)): string; /** * Get a string representation of the range. * @memberof Range * @returns {string} */ toString(): string; /** * Get a JSON representation of the range * @memberof Range * @returns {Object} Returns a JSON object structured as: * `{"mathjs": "Range", "start": 2, "end": 4, "step": 1}` */ toJSON(): RangeJSON; } | null; /** * Instantiate a Range from a JSON object * @memberof Range * @param {Object} json A JSON object structured as: * `{"mathjs": "Range", "start": 2, "end": 4, "step": 1}` * @return {Range} */ fromJSON(json: RangeJSON): { /** * Type identifier */ readonly type: string; /** * Range type flag */ readonly isRange: boolean; /** * Start value of the range (inclusive) */ start: number; /** * End value of the range (exclusive) */ end: number; /** * Step size for the range */ step: number; /** * Cached primitive array representation */ "__#private@#cache": number[] | null; "__#private@#cacheStart"?: number; "__#private@#cacheEnd"?: number; "__#private@#cacheStep"?: number; /** * Create a clone of the range * @return {Range} clone */ clone(): /*elided*/ any; /** * Retrieve the size of the range. * Returns an array containing one number, the number of elements in the range. * @memberof Range * @returns {number[]} size */ size(): number[]; /** * Calculate the minimum value in the range * @memberof Range * @return {number | undefined} min */ min(): number | undefined; /** * Calculate the maximum value in the range * @memberof Range * @return {number | undefined} max */ max(): number | undefined; /** * Execute a callback function for each value in the range. * @memberof Range * @param {function} callback The callback method is invoked with three * parameters: the value of the element, the index * of the element, and the Range being traversed. */ forEach(callback: RangeForEachCallback): void; /** * Execute a callback function for each value in the Range, and return the * results as an array * @memberof Range * @param {function} callback The callback method is invoked with three * parameters: the value of the element, the index * of the element, and the Matrix being traversed. * @returns {Array} array */ map(callback: RangeMapCallback): T[]; /** * Create an Array with a copy of the Ranges data * @memberof Range * @returns {Array} array */ toArray(): number[]; /** * Get the primitive value of the Range, a one dimensional array * @memberof Range * @returns {Array} array */ valueOf(): number[]; /** * Get a string representation of the range, with optional formatting options. * Output is formatted as 'start:step:end', for example '2:6' or '0:0.2:11' * @memberof Range * @param {Object | number | function} [options] Formatting options. See * lib/utils/number:format for a * description of the available * options. * @returns {string} str */ format(options?: RangeFormatOptions | number | ((value: number) => string)): string; /** * Get a string representation of the range. * @memberof Range * @returns {string} */ toString(): string; /** * Get a JSON representation of the range * @memberof Range * @returns {Object} Returns a JSON object structured as: * `{"mathjs": "Range", "start": 2, "end": 4, "step": 1}` */ toJSON(): RangeJSON; }; }>; /** * Ready-made `Range` class (the factory instantiated with no dependencies), * exported for direct use from the package index — mirrors how core ships a * ready-made `Complex`/`Fraction`/`Unit` alongside its factory. */ declare const Range: { new (start?: number | bigint | BigNumber$1 | null, end?: number | bigint | BigNumber$1 | null, step?: number | bigint | BigNumber$1 | null): { /** * Type identifier */ readonly type: string; /** * Range type flag */ readonly isRange: boolean; /** * Start value of the range (inclusive) */ start: number; /** * End value of the range (exclusive) */ end: number; /** * Step size for the range */ step: number; /** * Cached primitive array representation */ "__#private@#cache": number[] | null; "__#private@#cacheStart"?: number; "__#private@#cacheEnd"?: number; "__#private@#cacheStep"?: number; /** * Create a clone of the range * @return {Range} clone */ clone(): /*elided*/ any; /** * Retrieve the size of the range. * Returns an array containing one number, the number of elements in the range. * @memberof Range * @returns {number[]} size */ size(): number[]; /** * Calculate the minimum value in the range * @memberof Range * @return {number | undefined} min */ min(): number | undefined; /** * Calculate the maximum value in the range * @memberof Range * @return {number | undefined} max */ max(): number | undefined; /** * Execute a callback function for each value in the range. * @memberof Range * @param {function} callback The callback method is invoked with three * parameters: the value of the element, the index * of the element, and the Range being traversed. */ forEach(callback: RangeForEachCallback): void; /** * Execute a callback function for each value in the Range, and return the * results as an array * @memberof Range * @param {function} callback The callback method is invoked with three * parameters: the value of the element, the index * of the element, and the Matrix being traversed. * @returns {Array} array */ map(callback: RangeMapCallback): T[]; /** * Create an Array with a copy of the Ranges data * @memberof Range * @returns {Array} array */ toArray(): number[]; /** * Get the primitive value of the Range, a one dimensional array * @memberof Range * @returns {Array} array */ valueOf(): number[]; /** * Get a string representation of the range, with optional formatting options. * Output is formatted as 'start:step:end', for example '2:6' or '0:0.2:11' * @memberof Range * @param {Object | number | function} [options] Formatting options. See * lib/utils/number:format for a * description of the available * options. * @returns {string} str */ format(options?: RangeFormatOptions | number | ((value: number) => string)): string; /** * Get a string representation of the range. * @memberof Range * @returns {string} */ toString(): string; /** * Get a JSON representation of the range * @memberof Range * @returns {Object} Returns a JSON object structured as: * `{"mathjs": "Range", "start": 2, "end": 4, "step": 1}` */ toJSON(): RangeJSON; }; /** * Parse a string into a range, * The string contains the start, optional step, and end, separated by a colon. * If the string does not contain a valid range, null is returned. * For example str='0:2:11'. * @memberof Range * @param {string} str * @return {Range | null} range */ parse(str: string): { /** * Type identifier */ readonly type: string; /** * Range type flag */ readonly isRange: boolean; /** * Start value of the range (inclusive) */ start: number; /** * End value of the range (exclusive) */ end: number; /** * Step size for the range */ step: number; /** * Cached primitive array representation */ "__#private@#cache": number[] | null; "__#private@#cacheStart"?: number; "__#private@#cacheEnd"?: number; "__#private@#cacheStep"?: number; /** * Create a clone of the range * @return {Range} clone */ clone(): /*elided*/ any; /** * Retrieve the size of the range. * Returns an array containing one number, the number of elements in the range. * @memberof Range * @returns {number[]} size */ size(): number[]; /** * Calculate the minimum value in the range * @memberof Range * @return {number | undefined} min */ min(): number | undefined; /** * Calculate the maximum value in the range * @memberof Range * @return {number | undefined} max */ max(): number | undefined; /** * Execute a callback function for each value in the range. * @memberof Range * @param {function} callback The callback method is invoked with three * parameters: the value of the element, the index * of the element, and the Range being traversed. */ forEach(callback: RangeForEachCallback): void; /** * Execute a callback function for each value in the Range, and return the * results as an array * @memberof Range * @param {function} callback The callback method is invoked with three * parameters: the value of the element, the index * of the element, and the Matrix being traversed. * @returns {Array} array */ map(callback: RangeMapCallback): T[]; /** * Create an Array with a copy of the Ranges data * @memberof Range * @returns {Array} array */ toArray(): number[]; /** * Get the primitive value of the Range, a one dimensional array * @memberof Range * @returns {Array} array */ valueOf(): number[]; /** * Get a string representation of the range, with optional formatting options. * Output is formatted as 'start:step:end', for example '2:6' or '0:0.2:11' * @memberof Range * @param {Object | number | function} [options] Formatting options. See * lib/utils/number:format for a * description of the available * options. * @returns {string} str */ format(options?: RangeFormatOptions | number | ((value: number) => string)): string; /** * Get a string representation of the range. * @memberof Range * @returns {string} */ toString(): string; /** * Get a JSON representation of the range * @memberof Range * @returns {Object} Returns a JSON object structured as: * `{"mathjs": "Range", "start": 2, "end": 4, "step": 1}` */ toJSON(): RangeJSON; } | null; /** * Instantiate a Range from a JSON object * @memberof Range * @param {Object} json A JSON object structured as: * `{"mathjs": "Range", "start": 2, "end": 4, "step": 1}` * @return {Range} */ fromJSON(json: RangeJSON): { /** * Type identifier */ readonly type: string; /** * Range type flag */ readonly isRange: boolean; /** * Start value of the range (inclusive) */ start: number; /** * End value of the range (exclusive) */ end: number; /** * Step size for the range */ step: number; /** * Cached primitive array representation */ "__#private@#cache": number[] | null; "__#private@#cacheStart"?: number; "__#private@#cacheEnd"?: number; "__#private@#cacheStep"?: number; /** * Create a clone of the range * @return {Range} clone */ clone(): /*elided*/ any; /** * Retrieve the size of the range. * Returns an array containing one number, the number of elements in the range. * @memberof Range * @returns {number[]} size */ size(): number[]; /** * Calculate the minimum value in the range * @memberof Range * @return {number | undefined} min */ min(): number | undefined; /** * Calculate the maximum value in the range * @memberof Range * @return {number | undefined} max */ max(): number | undefined; /** * Execute a callback function for each value in the range. * @memberof Range * @param {function} callback The callback method is invoked with three * parameters: the value of the element, the index * of the element, and the Range being traversed. */ forEach(callback: RangeForEachCallback): void; /** * Execute a callback function for each value in the Range, and return the * results as an array * @memberof Range * @param {function} callback The callback method is invoked with three * parameters: the value of the element, the index * of the element, and the Matrix being traversed. * @returns {Array} array */ map(callback: RangeMapCallback): T[]; /** * Create an Array with a copy of the Ranges data * @memberof Range * @returns {Array} array */ toArray(): number[]; /** * Get the primitive value of the Range, a one dimensional array * @memberof Range * @returns {Array} array */ valueOf(): number[]; /** * Get a string representation of the range, with optional formatting options. * Output is formatted as 'start:step:end', for example '2:6' or '0:0.2:11' * @memberof Range * @param {Object | number | function} [options] Formatting options. See * lib/utils/number:format for a * description of the available * options. * @returns {string} str */ format(options?: RangeFormatOptions | number | ((value: number) => string)): string; /** * Get a string representation of the range. * @memberof Range * @returns {string} */ toString(): string; /** * Get a JSON representation of the range * @memberof Range * @returns {Object} Returns a JSON object structured as: * `{"mathjs": "Range", "start": 2, "end": 4, "step": 1}` */ toJSON(): RangeJSON; }; }; declare class Dual { /** Function value (the real part). */ readonly value: number; /** First derivative (the ε coefficient). */ readonly deriv: number; constructor(value: number, deriv?: number); /** A constant (derivative 0). */ static constant(v: number): Dual; /** A seed variable (derivative 1) — the point of differentiation. */ static variable(v: number): Dual; add(o: Dual): Dual; sub(o: Dual): Dual; mul(o: Dual): Dual; div(o: Dual): Dual; neg(): Dual; /** Power with a constant real exponent: d(xᵏ) = k·xᵏ⁻¹·dx. */ powConst(k: number): Dual; /** General power a^b: d = a^b·(b'·ln a + b·a'/a). */ pow(o: Dual): Dual; private unary; sin(): Dual; cos(): Dual; tan(): Dual; exp(): Dual; log(): Dual; sqrt(): Dual; square(): Dual; abs(): Dual; sinh(): Dual; cosh(): Dual; tanh(): Dual; toString(): string; } /** Type guard for {@link Dual}. */ declare function isDual(x: unknown): x is Dual; /** * Canonical elementary-function derivative rules for forward-mode automatic * differentiation. This is the single source of truth for the chain rules, * shared by the scalar {@link Dual} (core) and the tensor `DualTensor` * (autograd) so neither reinvents them. * * Each rule is a pair of pure `number → number` functions: * - `primal(x)` — f(x) * - `deriv(x, y)` — f′(x), given both x and the already-computed y = f(x), * so output-reusing derivatives (exp, tanh, sqrt, cbrt, expm1) stay cheap. * * Keeping these as plain scalar functions (no `Dual`/`Tensor` allocation) is * what lets autograd's `Float64Array` element-wise loop stay allocation-free. * It is also the propagation path: a future accelerated `primal` in the * standard layer (WASM/SIMD batch kernels) can be swapped in here and every * consumer inherits the speedup without touching this contract. */ /** A forward-mode derivative rule for a unary elementary function. */ interface DualUnaryRule { /** f(x). */ readonly primal: (x: number) => number; /** f′(x), given x and y = f(x) (y lets exp/tanh/sqrt/… avoid recomputation). */ readonly deriv: (x: number, y: number) => number; } /** * The canonical table. Derivatives are stated in the cheapest exact form * (reusing y where that avoids a redundant transcendental call). */ declare const DUAL_UNARY_RULES: { exp: { primal: (x: number) => number; deriv: (_x: number, y: number) => number; }; expm1: { primal: (x: number) => number; deriv: (_x: number, y: number) => number; }; log: { primal: (x: number) => number; deriv: (x: number) => number; }; log2: { primal: (x: number) => number; deriv: (x: number) => number; }; log10: { primal: (x: number) => number; deriv: (x: number) => number; }; log1p: { primal: (x: number) => number; deriv: (x: number) => number; }; sin: { primal: (x: number) => number; deriv: (x: number) => number; }; cos: { primal: (x: number) => number; deriv: (x: number) => number; }; tan: { primal: (x: number) => number; deriv: (x: number) => number; }; asin: { primal: (x: number) => number; deriv: (x: number) => number; }; acos: { primal: (x: number) => number; deriv: (x: number) => number; }; atan: { primal: (x: number) => number; deriv: (x: number) => number; }; sinh: { primal: (x: number) => number; deriv: (x: number) => number; }; cosh: { primal: (x: number) => number; deriv: (x: number) => number; }; tanh: { primal: (x: number) => number; deriv: (_x: number, y: number) => number; }; asinh: { primal: (x: number) => number; deriv: (x: number) => number; }; acosh: { primal: (x: number) => number; deriv: (x: number) => number; }; atanh: { primal: (x: number) => number; deriv: (x: number) => number; }; sqrt: { primal: (x: number) => number; deriv: (_x: number, y: number) => number; }; cbrt: { primal: (x: number) => number; deriv: (_x: number, y: number) => number; }; square: { primal: (x: number) => number; deriv: (x: number) => number; }; reciprocal: { primal: (x: number) => number; deriv: (x: number) => number; }; abs: { primal: (x: number) => number; deriv: (x: number) => number; }; sign: { primal: (x: number) => number; deriv: () => number; }; }; /** Name of a rule in {@link DUAL_UNARY_RULES}. */ type DualUnaryRuleName = keyof typeof DUAL_UNARY_RULES; /** * Named mathematical constants (plain `number`). * * These mirror the constants documented in `docs/reference/constants.md` and the * familiar `Math.*` values, exported as first-class named bindings so callers can * `import { PI, E, TAU } from '@danielsimonjr/mathts-core'`. The imaginary unit * `I` and the type-specific constants (`COMPLEX_*`, `BIGNUMBER_*`, `FRACTION_*`) * live with their respective types. */ /** Ratio of a circle's circumference to its diameter. */ declare const PI: number; /** Euler's number, the base of the natural logarithm. */ declare const E: number; /** Full-circle constant, `2·PI`. */ declare const TAU: number; /** Golden ratio, `(1 + √5) / 2`. */ declare const PHI: number; /** Square root of 2. */ declare const SQRT2: number; /** Square root of one-half. */ declare const SQRT1_2: number; /** Natural logarithm of 2. */ declare const LN2: number; /** Natural logarithm of 10. */ declare const LN10: number; /** Base-2 logarithm of E. */ declare const LOG2E: number; /** Base-10 logarithm of E. */ declare const LOG10E: number; /** * Fraction (rational number) implementation * @module @danielsimonjr/mathts-core/types/fraction */ /** * Check if a value is a Fraction */ declare function isFraction(value: unknown): value is Fraction; /** * Fraction class for exact rational arithmetic * Uses bigint for arbitrary precision numerator and denominator. * All fractions are automatically reduced to lowest terms. */ declare class Fraction implements IFraction { readonly type = "Fraction"; readonly numerator: bigint; readonly denominator: bigint; constructor(numerator: bigint | number | string | Fraction, denominator?: bigint | number | string | Fraction); /** * Create a Fraction from a number (with optional precision) */ static fromNumber(n: number, maxDenominator?: bigint): Fraction; /** * Create a Fraction from a decimal string */ static fromDecimalString(str: string): Fraction; /** * Parse a fraction from a string * Supports formats: "3/4", "-3/4", "3", "3.14", "0.(3)" */ static parse(str: string): Fraction; /** * Create a Fraction from a JSON object */ static fromJSON(json: { n: string; d: string; } | { numerator: string; denominator: string; }): Fraction; /** * Compare two fractions * @returns -1, 0, or 1 */ static compare(a: Fraction, b: Fraction): number; valueOf(): number; toString(): string; toJSON(): { mathjs: string; n: string; d: string; }; /** * Convert to number */ toNumber(): number; /** * Convert to decimal string with specified precision */ toDecimal(precision?: number): string; /** * Convert to LaTeX string */ toLatex(): string; /** * Convert to mixed number representation */ toMixed(): { whole: bigint; numerator: bigint; denominator: bigint; }; /** * Addition: a/b + c/d = (ad + bc) / bd */ add(other: Scalar): Fraction; /** * Subtraction: a/b - c/d = (ad - bc) / bd */ subtract(other: Scalar): Fraction; /** * Multiplication: a/b * c/d = ac / bd */ multiply(other: Scalar): Fraction; /** * Division: a/b ÷ c/d = ad / bc */ divide(other: Scalar): Fraction; mul(other: Scalar): Fraction; sub(other: Scalar): Fraction; div(other: Scalar): Fraction; /** * Negation: -(a/b) = -a/b */ negate(): Fraction; /** * Absolute value: |a/b| */ abs(): Fraction; /** * Reciprocal: b/a */ inverse(): Fraction; /** * Power (integer exponent) */ pow(n: number | bigint): Fraction; /** * Modulo operation */ mod(other: Fraction): Fraction; /** * Check equality */ equals(other: Fraction): boolean; /** * Check if less than */ lessThan(other: Fraction): boolean; /** * Check if less than or equal */ lessThanOrEqual(other: Fraction): boolean; /** * Check if greater than */ greaterThan(other: Fraction): boolean; /** * Check if greater than or equal */ greaterThanOrEqual(other: Fraction): boolean; /** * Compare with another fraction * @returns -1, 0, or 1 */ compareTo(other: Fraction): number; compare(other: Fraction): number; /** * Return fraction already in lowest terms (no-op since constructor reduces) */ simplify(): Fraction; /** * Check if this is zero */ isZero(): boolean; /** * Check if this is positive */ isPositive(): boolean; /** * Check if this is negative */ isNegative(): boolean; /** * Check if this is an integer */ isInteger(): boolean; /** * Check if this is a unit fraction (1/n) */ isUnit(): boolean; /** * Floor: largest integer ≤ this */ floor(): Fraction; /** * Ceiling: smallest integer ≥ this */ ceil(): Fraction; /** * Round to nearest integer */ round(): Fraction; /** * Truncate (round toward zero) */ trunc(): Fraction; /** * Get the sign: -1, 0, or 1 */ sign(): number; /** * Clone this fraction */ clone(): Fraction; /** * Get the GCD of numerator and denominator (always 1 since we reduce) */ gcd(): bigint; /** * Get continued fraction representation */ toContinuedFraction(): bigint[]; /** * Create fraction from continued fraction */ static fromContinuedFraction(cf: bigint[]): Fraction; /** * Mediant of two fractions: (a+c)/(b+d) * Used in Stern-Brocot tree and Farey sequences */ mediant(other: Fraction): Fraction; } /** * Common fraction constants */ declare const FRACTION_ZERO: Fraction; declare const FRACTION_ONE: Fraction; declare const FRACTION_NEG_ONE: Fraction; declare const FRACTION_HALF: Fraction; declare const FRACTION_THIRD: Fraction; declare const FRACTION_QUARTER: Fraction; /** * BigNumber (arbitrary precision decimal) implementation * @module @danielsimonjr/mathts-core/types/bignumber */ /** * Check if a value is a BigNumber */ declare function isBigNumber(value: unknown): value is BigNumber; /** * Configuration for BigNumber operations */ interface BigNumberConfig { /** Number of significant digits (default: 64) */ precision: number; /** Rounding mode (default: 'halfUp') */ rounding: RoundingMode; /** Minimum exponent (default: -1e9) */ minExponent: number; /** Maximum exponent (default: 1e9) */ maxExponent: number; } type RoundingMode = 'up' | 'down' | 'ceil' | 'floor' | 'halfUp' | 'halfDown' | 'halfEven' | 'halfCeil' | 'halfFloor'; /** * BigNumber class for arbitrary precision decimal arithmetic * * Internally stores: sign * coefficient * 10^exponent * where coefficient is a bigint with the significant digits. */ declare class BigNumber implements MathTSValue { readonly type = "BigNumber"; /** * Duck-typing marker for Decimal.js / mathjs formatter compatibility. * Allows external code that checks `obj.isBigNumber === true` to identify * this class without an `instanceof` check. */ readonly isBigNumber = true; private readonly _sign; private readonly _coefficient; private readonly _exponent; private readonly _isNaN; private readonly _isInfinite; private constructor(); /** * Create a BigNumber from a number */ static fromNumber(n: number): BigNumber; /** * Create a BigNumber from a string */ static parse(str: string): BigNumber; /** * Create from bigint */ static fromBigInt(n: bigint): BigNumber; /** * Create a BigNumber from a JSON object */ static fromJSON(json: { value: string; }): BigNumber; /** * Get/set global configuration */ static config(newConfig?: Partial): BigNumberConfig; /** * Reset configuration to defaults */ static resetConfig(): void; /** * Compare two BigNumbers * @returns -1, 0, or 1 */ static compare(a: BigNumber, b: BigNumber): number; private static compareMagnitude; valueOf(): number; /** * Convert to a JS number. * Alias for `valueOf()` — provided for Decimal.js / mathjs formatter * duck-typing compatibility. */ toNumber(): number; toString(): string; toJSON(): { mathjs: string; value: string; }; /** * Convert to fixed-point notation. * * When called with no argument (or `undefined`) returns the full fixed-point * string representation without rounding — matching Decimal.js semantics where * `toFixed()` is equivalent to a lossless fixed-point stringify. * When called with a non-negative integer `decimalPlaces`, rounds and formats * to exactly that many digits after the decimal point. */ toFixed(decimalPlaces?: number): string; private toFixedInternal; /** * Convert to exponential notation */ toExponential(decimalPlaces?: number): string; /** * Convert to precision */ toPrecision(significantDigits?: number): string; /** * Convert to bigint (truncated) */ toBigInt(): bigint; /** * Binary string representation, e.g. `255 -> '0b11111111'`, `0.5 -> '0b0.1'`. * Mirrors Decimal.js `toBinary()`. Negatives carry a leading `-`. */ toBinary(): string; /** * Octal string representation, e.g. `8 -> '0o10'`. * Mirrors Decimal.js `toOctal()`. */ toOctal(): string; /** * Hexadecimal string representation, e.g. `255 -> '0xff'`, `10.5 -> '0xa.8'`. * Mirrors Decimal.js `toHexadecimal()`. */ toHexadecimal(): string; /** * Shared radix formatter for {@link toBinary}/{@link toOctal}/{@link toHexadecimal}. * Integers and terminating fractions are exact; a non-terminating fraction is * truncated at `maxFractionDigits` radix digits (a safety bound — the common * use is integer formatting). */ private toRadixString; /** * Addition */ add(other: Scalar | BigNumber | number | string): BigNumber; /** * Subtraction */ subtract(other: Scalar | BigNumber | number | string): BigNumber; /** * Alias for subtract — mathjs / Decimal.js compatibility. */ sub(other: Scalar | BigNumber | number | string): BigNumber; /** * Multiplication */ multiply(other: Scalar | BigNumber | number | string): BigNumber; /** * Alias for multiply — mathjs / Decimal.js compatibility. */ mul(other: Scalar | BigNumber | number | string): BigNumber; /** * Alias for multiply — Decimal.js calling convention (used by the Unit). */ times(other: Scalar | BigNumber | number | string): BigNumber; /** * Division */ divide(other: Scalar | BigNumber | number | string): BigNumber; /** * Alias for divide — Decimal.js calling convention (used by the Unit). */ div(other: Scalar | BigNumber | number | string): BigNumber; /** * Negation */ negate(): BigNumber; /** * Absolute value */ abs(): BigNumber; /** * Power (integer exponent) */ pow(n: number | bigint): BigNumber; /** * Square root */ sqrt(): BigNumber; equals(other: BigNumber | number | string): boolean; lessThan(other: BigNumber | number | string): boolean; lessThanOrEqual(other: BigNumber | number | string): boolean; greaterThan(other: BigNumber | number | string): boolean; greaterThanOrEqual(other: BigNumber | number | string): boolean; compareTo(other: BigNumber | number | string): number; compare(other: BigNumber | number | string): number; /** * Returns true iff this > other. * Accepts the same argument types as `add`/`multiply` (BigNumber, number, or string). * Named `gt` for Decimal.js / mathjs formatter compatibility. */ gt(other: BigNumber | number | string): boolean; /** * Round to specified decimal places */ round(decimalPlaces?: number, mode?: RoundingMode): BigNumber; private shouldRound; /** * Round to specified precision (significant digits) */ roundToPrecision(precision: number, mode?: RoundingMode): BigNumber; floor(): BigNumber; ceil(): BigNumber; trunc(): BigNumber; /** * Round to `n` significant decimal digits and return a new BigNumber. * Delegates to `roundToPrecision`, using the global rounding mode unless * an explicit `roundingMode` is supplied. * * Named `toSignificantDigits` for Decimal.js / mathjs formatter compatibility. * When `n` is undefined the value is returned unchanged (no rounding). */ toSignificantDigits(n?: number, roundingMode?: RoundingMode): BigNumber; /** * The decimal exponent of this number: `floor(log10(|x|))`. * * Matches Decimal.js semantics: * - `12345` → `4` (5 digits → the most-significant place is 10^4) * - `0.0123` → `-2` (first significant digit is at 10^-2) * - `100` → `2` * - `0.01` → `-2` * - `0` → `0` (by convention; `isZero()` can be used to distinguish) * * For special values (NaN, ±Infinity) returns 0 — callers check * `isFinite()` / `isNaN()` before using `.e`. */ get e(): number; /** * Modulo (remainder after division) * Result has the same sign as the dividend (this). */ mod(other: Scalar | BigNumber | number | string): BigNumber; /** * Sine of this BigNumber (in radians) * Uses Taylor series: sin(x) = x - x^3/3! + x^5/5! - ... */ sin(): BigNumber; /** * Cosine of this BigNumber (in radians) * Uses Taylor series: cos(x) = 1 - x^2/2! + x^4/4! - ... */ cos(): BigNumber; /** * Tangent of this BigNumber (in radians) * tan(x) = sin(x) / cos(x) */ tan(): BigNumber; /** * Arcsine of this BigNumber * Returns value in [-PI/2, PI/2] */ asin(): BigNumber; /** * Arccosine of this BigNumber * Returns value in [0, PI] */ acos(): BigNumber; /** * Arctangent of this BigNumber * Returns value in (-PI/2, PI/2) * Uses Taylor series with argument reduction for convergence. */ atan(): BigNumber; /** * Two-argument arctangent: atan2(y, x) * this = y, argument = x * Returns angle in (-PI, PI] */ atan2(x: BigNumber): BigNumber; /** * Hyperbolic sine: sinh(x) = (e^x - e^(-x)) / 2 */ sinh(): BigNumber; /** * Hyperbolic cosine: cosh(x) = (e^x + e^(-x)) / 2 */ cosh(): BigNumber; /** * Hyperbolic tangent: tanh(x) = sinh(x) / cosh(x) */ tanh(): BigNumber; /** * Inverse hyperbolic sine: asinh(x) = ln(x + sqrt(x^2 + 1)) */ asinh(): BigNumber; /** * Inverse hyperbolic cosine: acosh(x) = ln(x + sqrt(x^2 - 1)) * Domain: x >= 1 */ acosh(): BigNumber; /** * Inverse hyperbolic tangent: atanh(x) = 0.5 * ln((1+x)/(1-x)) * Domain: -1 < x < 1 */ atanh(): BigNumber; /** * Exponential function: e^x * Uses Taylor series: e^x = 1 + x + x^2/2! + x^3/3! + ... * With argument reduction: e^x = (e^(x/2^k))^(2^k) for faster convergence. */ exp(): BigNumber; /** * Natural logarithm: ln(x) * Uses the AGM (arithmetic-geometric mean) method for fast convergence. * Fallback: series ln((1+y)/(1-y)) = 2*(y + y^3/3 + y^5/5 + ...) where y = (x-1)/(x+1) */ ln(): BigNumber; /** * Base-10 logarithm: log10(x) = ln(x) / ln(10) */ log10(): BigNumber; /** * Base-2 logarithm: log2(x) = ln(x) / ln(2) */ log2(): BigNumber; /** * Cube root * Uses Newton-Raphson iteration. */ cbrt(): BigNumber; /** * e^x - 1 (more precise than exp(x) - 1 for small x) * Uses Taylor series directly: expm1(x) = x + x^2/2! + x^3/3! + ... */ expm1(): BigNumber; /** * ln(1 + x) (more precise than ln(1 + x) for small x) */ log1p(): BigNumber; /** * Hypotenuse: sqrt(this^2 + other^2) */ hypot(other: BigNumber): BigNumber; /** Reduce angle to [-PI, PI] range */ private _reduceAngle; /** Taylor series for sin(x), assumes x is in [-PI, PI] */ private _sinTaylor; /** Taylor series for cos(x), assumes x is in [-PI, PI] */ private _cosTaylor; /** Taylor series for atan(x), assumes |x| <= 0.5 */ private _atanTaylor; isNaN(): boolean; isFinite(): boolean; isInfinite(): boolean; isZero(): boolean; isPositive(): boolean; isNegative(): boolean; isInteger(): boolean; sign(): number; clone(): BigNumber; private ensureBigNumber; private alignExponents; private normalize; } /** * Common BigNumber constants */ declare const BIGNUMBER_ZERO: BigNumber; declare const BIGNUMBER_ONE: BigNumber; declare const BIGNUMBER_NEG_ONE: BigNumber; declare const BIGNUMBER_TEN: BigNumber; declare const BIGNUMBER_PI: BigNumber; declare const BIGNUMBER_E: BigNumber; declare const BIGNUMBER_LN2: BigNumber; declare const BIGNUMBER_LN10: BigNumber; /** Any scalar core can do arithmetic on. */ type NumericScalar = number | bigint | Complex | Fraction | BigNumber; /** Add two scalar values, `x + y`. */ declare function addScalar(x: NumericScalar, y: NumericScalar): NumericScalar; /** Subtract two scalar values, `x − y` (order preserved through promotion). */ declare function subtractScalar(x: NumericScalar, y: NumericScalar): NumericScalar; /** Multiply two scalar values, `x · y`. */ declare function multiplyScalar(x: NumericScalar, y: NumericScalar): NumericScalar; /** Divide two scalar values, `x ÷ y` (order preserved through promotion). */ declare function divideScalar(x: NumericScalar, y: NumericScalar): NumericScalar; /** * Raise `base` to the power `exp`, treating `exp` as a real exponent. * * The exact `.pow()` of an exact type (Fraction/BigNumber) only supports INTEGER * exponents. A non-integer exponent of an exact base is generally irrational, so * it cannot stay exact — those cases fall back to double-precision `Math.pow`, * returning a plain `number`. (Without this guard, `BigNumber.pow(0.5)` silently * returned 1 and `Fraction.pow(0.5)` threw `BigInt(0.5)`.) */ declare function pow(base: NumericScalar, exp: NumericScalar): NumericScalar; /** Absolute value. `abs(Complex)` returns the magnitude (a real number). */ declare function abs(x: NumericScalar): NumericScalar; /** Round toward zero (truncate). Complex components are truncated independently. */ declare function fix(x: NumericScalar): NumericScalar; /** * Round to the nearest integer, half toward +∞ — matching `Math.round` and * `Fraction.round`. `BigNumber.round` defaults to half-away-from-zero, so it is * given `'halfCeil'` explicitly; otherwise negative half-integers would round * type-dependently (`round(-2.5)` = −2 for number/Fraction but −3 for BigNumber). * Complex components are rounded independently. */ declare function round(x: NumericScalar): NumericScalar; /** * Equality. Floating-point operands compare with the configured tolerance * (`relTol`/`absTol`); exact types (Fraction, BigNumber) compare exactly — * tolerance is meaningless for an exact rational/decimal. */ declare function equal(x: NumericScalar, y: NumericScalar, relTol?: number, absTol?: number): boolean; /** * True for values math treats as real-numeric: `number`, `bigint`, `boolean`, * `Fraction`, `BigNumber`. Mirrors mathjs semantics — `boolean` counts (it * coerces to 0/1), while `Complex` is intentionally NOT numeric (callers test it * separately), so `isNumeric(complex)` is `false`. The relocated Unit uses this as * its value-type gate (`isNumeric(value) || isComplex(value)`), and mathjs accepts * `new Unit(true)` — so booleans must pass. */ declare function isNumeric(x: unknown): boolean; /** * Convert any scalar to a plain JS `number`. A non-real `Complex` (nonzero * imaginary part) has no real-number value and throws. */ declare function number(x: NumericScalar): number; /** * Typed error classes for the Unit. Kept in their own module (with no Unit * imports) so both the merged `Unit` (`Unit.ts`) and the `core/src/types/unit.ts` * compatibility surface can import them without a circular dependency, and so * callers can `catch (e) { if (e instanceof UnitParseError) … }` as before the * two Unit implementations merged. */ /** Thrown when a unit notation string cannot be parsed against the registry. */ declare class UnitParseError extends Error { readonly name = "UnitParseError"; constructor(message: string); } /** Thrown when an operation requires two units to share a base dimension and they do not. */ declare class DimensionMismatchError extends Error { readonly name = "DimensionMismatchError"; constructor(message: string); } /** * Unit definitions for the Unit type. * * The seven SI base units, plus common derived and imperial units. Each * definition stores its multiplicative factor (to base SI) and dimensional * exponents. Temperatures carry an additive offset for the K↔°C↔°F * conversions. * * @module @danielsimonjr/mathts-core/types/unit-definitions */ /** * The seven SI base dimensions, expressed as a vector of (possibly fractional) * exponents. */ interface Dimensions { /** Length, base unit metre */ length: number; /** Mass, base unit kilogram */ mass: number; /** Time, base unit second */ time: number; /** Electric current, base unit ampere */ current: number; /** Thermodynamic temperature, base unit kelvin */ temperature: number; /** Amount of substance, base unit mole */ amount: number; /** Luminous intensity, base unit candela */ luminosity: number; } /** * The zero-dimensional vector (a dimensionless quantity). */ declare const DIMENSIONLESS: Dimensions; /** * Construct a Dimensions record from a partial spec. * * Missing fields default to 0, so `dim({ length: 1 })` returns the dimension * vector for length. */ declare function dim(partial: Partial): Dimensions; /** * Definition of a single named unit. */ interface UnitDef { /** Multiplicative factor: value-in-base = input * multiplier (+ offset). */ multiplier: number; /** Additive offset, used for non-multiplicative units like °C and °F. */ offset?: number; /** Dimensional signature. */ dimensions: Dimensions; /** Whether SI prefixes (k, M, µ, …) may be applied to this notation. */ prefixable?: boolean; } /** * The seven SI base units. */ declare const BASE_UNITS: Record; /** * Common derived units (SI named units, imperial units, and convenience units). * * This is *not* exhaustive — it covers the most common ~40 units needed for * dimensional-analysis tests. Add more as needed by downstream callers. */ declare const DERIVED_UNITS: Record; /** * Combined registry — both base and derived units in one map. */ declare const ALL_UNITS: Record; /** * Convenience aliases mapping common Unicode/ASCII variants to the canonical * notation key. Used by the parser; not part of the registered notation set. */ declare const UNIT_ALIASES: Record; /** * Lookup an exact (non-prefixed) unit definition. */ declare function getUnitDef(name: string): UnitDef | undefined; /** * SI prefixes for the Unit type. * * Maps single- and double-letter prefixes to their multiplicative factor in * base units. The full SI prefix range (from y = 1e-24 to Y = 1e24) is * supported, plus the binary prefixes used for digital information units. * * @module @danielsimonjr/mathts-core/types/unit-prefixes */ /** * Standard SI prefixes (mass/length/energy/etc.). * * Note the ambiguity-resolution priority: longer prefixes (e.g. `da`) * must be tried before single-letter ones (`d`, `a`) in parsers. */ declare const SI_PREFIXES: Record; /** * Set of "good" prefixes to use in `toBest()` selection. * * Excludes `h`, `da`, `d`, `c` (commonly only used for centimeters and similar * legacy notations); using these in `toBest()` would produce awkward outputs * like "0.4 hg" instead of "40 g". */ declare const BEST_PREFIXES: ReadonlyArray; /** * Look up an SI prefix multiplier. Returns `undefined` if not a known prefix. */ declare function getPrefix(name: string): number | undefined; /** * MathTS typed-function Integration * * Creates a configured typed-function instance with MathTS types * for runtime type dispatch across numeric types, matrices, and more. * * This module directly uses the typed-function library API without * any intermediate abstraction layers. * * Supports WASM-accelerated dispatch when available. * * @packageDocumentation */ /** * Initialize WASM dispatch for typed-function (optional, improves performance) * * Uses the unified typed.init() API to enable WASM-accelerated dispatch * with automatic fallback to pure JS when WASM is unavailable. * * @param options - Initialization options * @returns Promise resolving to true if WASM was initialized successfully */ declare function initTypedWasm(options?: { preferWasm?: boolean; }): Promise; /** * Check if WASM dispatch is available */ declare function isTypedWasmAvailable(): boolean; /** * Any concrete implementation accepted when *declaring* a typed signature. * * typed-function's published `SignatureFunction` is `(...args: unknown[]) => * unknown`, which is correct for *internal/output* positions (where the stored * impl is later CALLED with validated args) but wrong as an *input* type: * under `strictFunctionTypes`, function parameters are contravariant, so a * concrete impl such as `(a: number, b: number) => number` is NOT assignable * to an `unknown[]` parameter list (`unknown` is not assignable to `number`). * The correct top-type for "any function" in an input position uses `never` * parameters — every function is assignable to it because `never` is * assignable to every parameter type. This is exactly the set of values * typed-function genuinely accepts when declaring signatures. */ type SignatureImpl = (...args: never[]) => unknown; /** Signature record accepted by the MathTS typed factory (see {@link SignatureImpl}). */ type SignatureRecord = Record; /** * The MathTS typed-function factory type. * * Structurally identical to typed-function's {@link TypedInstance} except its * call signatures accept implementations declared with concrete parameter * types (see {@link SignatureImpl}). All instance methods are inherited * unchanged via `Omit` (a mapped type, which drops the * overly-strict published call signatures while preserving every method). */ interface MathTSTyped extends Omit { (name: string, signatures: SignatureRecord): TypedFunction; (signatures: SignatureRecord): TypedFunction; (...args: Array): TypedFunction; referToSelf: (callback: (self: TypedFunction) => SignatureImpl) => ReferToSelf; referTo: (...args: [...string[], (...fns: SignatureFunction[]) => SignatureImpl]) => ReferTo; } /** * Type definition for typed-function */ interface TypeDef { name: string; test: (x: unknown) => boolean; } /** * Conversion definition for typed-function */ interface ConversionDef { from: string; to: string; convert: (value: unknown) => unknown; } declare const isNumber: (x: unknown) => x is number; declare const isBoolean: (x: unknown) => x is boolean; declare const isString: (x: unknown) => x is string; declare const isBigInt: (x: unknown) => x is bigint; declare const isArray: (x: unknown) => x is unknown[]; declare const isFunction: (x: unknown) => x is (...args: unknown[]) => unknown; declare const isObject: (x: unknown) => x is object; declare const isNull: (x: unknown) => x is null; declare const isUndefined: (x: unknown) => x is undefined; /** * Check if value is a Matrix (duck typing until Matrix class is implemented) */ declare const isMatrix: (x: unknown) => boolean; /** * Check if value is a DenseMatrix */ declare const isDenseMatrix: (x: unknown) => boolean; /** * Check if value is a SparseMatrix */ declare const isSparseMatrix: (x: unknown) => boolean; /** * Check if value is a Unit * * Recognises both the native {@link Unit} class (which exposes `value`, * `dimensions`, and `notation`) and the legacy duck-typed shape used by * mathjs-compatibility shims (`{ value, unit, type }`). */ declare const isUnit: (x: unknown) => boolean; /** * Extended type definition with optional WASM mask support */ interface MathTSTypeDef extends TypeDef { /** Optional WASM type mask for accelerated dispatch (auto-registered when WASM available) */ wasmMask?: number; } /** * MathTS-specific types to add to typed-function. * Note: Most primitive types (number, boolean, string, etc.) are already built into typed-function * * When WASM is available, custom type masks are automatically registered for efficient dispatch. */ declare const MATHTS_TYPES: MathTSTypeDef[]; declare const MATHTS_CONVERSIONS: ConversionDef[]; /** * Create a new MathTS typed instance * * This creates an isolated typed universe with MathTS types and conversions. * Uses typed-function's addType() API which automatically registers WASM * type masks when available. * * @returns A new typed-function instance configured for MathTS * * @example * ```typescript * const myTyped = createMathTSTyped(); * * const add = myTyped('add', { * 'number, number': (a, b) => a + b, * 'Complex, Complex': (a, b) => a.add(b), * 'Fraction, Fraction': (a, b) => a.add(b), * 'BigNumber, BigNumber': (a, b) => a.add(b), * }); * ``` */ declare function createMathTSTyped(): TypedInstance; /** * Default MathTS typed instance * * This is the primary typed-function instance used throughout MathTS. * It comes pre-configured with all MathTS types and conversions. * * @example * ```typescript * import { mathTyped, Complex, Fraction, BigNumber } from '@danielsimonjr/mathts-core'; * * // Create a polymorphic add function * const add = mathTyped('add', { * 'number, number': (a, b) => a + b, * 'Complex, Complex': (a, b) => a.add(b), * 'Fraction, Fraction': (a, b) => a.add(b), * 'BigNumber, BigNumber': (a, b) => a.add(b), * }); * * // Works with automatic type coercion * add(1, 2); // 3 * add(new Complex(1, 2), new Complex(3, 4)); // Complex(4, 6) * add(new Fraction(1, 2), new Fraction(1, 3)); // Fraction(5, 6) * add(1, new Complex(2, 3)); // Complex(3, 3) - auto-converts * ``` */ declare const mathTyped: MathTSTyped; /** * TypeRegistry class for managing custom type registrations * This is a MathTS utility, not from typed-function */ declare class TypeRegistry { private types; private conversions; private instance; /** * Register a new type */ registerType(name: string, test: (x: unknown) => x is T): this; /** * Register a type conversion */ registerConversion(from: string, to: string, convert: (value: From) => To): this; /** * Check if a type is registered */ hasType(name: string): boolean; /** * Check if a conversion is registered */ hasConversion(from: string, to: string): boolean; /** * Get all registered type names */ getTypeNames(): string[]; /** * Build a typed-function instance from the registry */ build(): TypedInstance; /** * Clear all registered types and conversions */ clear(): void; } /** * Helper to create a typed function with the MathTS typed instance */ declare function createTypedFunction(name: string, signatures: { [signature: string]: (...args: unknown[]) => T; }, typedInstance?: TypedInstance): (...args: unknown[]) => T; declare function registerNativeTypes(): void; /** * MathTS Function Factory * * Provides a factory pattern for creating MathTS functions with: * - Typed function dispatch via typed-function * - Dependency injection for inter-function references * - Backend selection integration * - Lazy loading support * * @packageDocumentation */ /** * Configuration for MathTS instance */ interface MathTSConfig { /** Numeric precision (for BigNumber) */ precision: number; /** Default matrix type */ matrix: 'Matrix' | 'Array'; /** Number type for parsing */ number: 'number' | 'BigNumber' | 'Fraction'; /** Enable predictable randomness */ randomSeed: string | null; /** Epsilon for floating point comparison */ epsilon: number; /** Preferred backend for matrix operations */ preferredBackend: 'auto' | 'js' | 'wasm' | 'gpu'; /** Minimum elements to use WASM backend */ wasmThreshold: number; /** Minimum elements to use GPU backend */ gpuThreshold: number; /** Enable parallel processing */ parallelEnabled: boolean; /** Minimum elements to parallelize */ parallelThreshold: number; } /** * Default MathTS configuration */ declare const DEFAULT_CONFIG: MathTSConfig; /** * Factory function definition */ interface FactoryFunction { /** Name of the function */ name: string; /** Dependencies required by this function */ dependencies: string[]; /** Factory that creates the function given dependencies */ factory: (deps: FactoryDependencies) => T; } /** * Dependencies passed to factory functions */ interface FactoryDependencies { /** MathTS configuration */ config: MathTSConfig; /** typed-function instance */ typed: TypedInstance; /** Registered functions (for cross-references) */ [key: string]: unknown; } /** * Import definition for a factory function */ type FactoryImport = FactoryFunction | (() => Promise); /** * MathTS function registry */ declare class FunctionRegistry { private factories; private instances; private dependencies; private creating; constructor(config?: Partial, typed?: TypedInstance); /** * Register a factory function */ register(factory: FactoryFunction): void; /** * Register multiple factory functions */ registerAll(factories: FactoryFunction[]): void; /** * Get or create a function by name */ get(name: string): TypedFunction; /** * Check if a function is registered */ has(name: string): boolean; /** * Get all registered function names */ names(): string[]; /** * Update configuration */ updateConfig(config: Partial): void; /** * Get current configuration */ getConfig(): MathTSConfig; } /** * Create a factory function definition * * @example * ```typescript * export const addFactory = createFactory('add', ['typed'], ({ typed }) => * typed('add', { * 'number, number': (a, b) => a + b, * 'Complex, Complex': (a, b) => ({ re: a.re + b.re, im: a.im + b.im }), * }) * ); * ``` */ declare function createFactory(name: string, dependencies: string[], factory: (deps: FactoryDependencies) => T): FactoryFunction; declare const registry: FunctionRegistry; declare const math: { /** * Get a registered function */ get: (name: string) => TypedFunction; /** * Register a factory function */ register: (factory: FactoryFunction) => void; /** * Get configuration */ config: () => MathTSConfig; /** * Update configuration */ configure: (config: Partial) => void; }; /** * Numerically stable reduction primitives. * * Floating-point addition is not associative, so *how* you accumulate decides how much error you * carry. These are the algorithms the established numerical stack uses, and the reason it is * trusted. * * Measured on this repo's own reductions before these existed — 1e6 copies of `0.1`, exact answer * 100000: * * | accumulation | relative error | * | ------------------------------- | -------------- | * | naive `s += x` | **1.3e-11** | * | pairwise (this, = NumPy's algo) | **2.9e-16** | * | Neumaier compensated (`fsum`) | **0** (exact) | * * NumPy 2.3.4 reports 2.9e-16 on the same input — we are now at parity. Before this, we were * ~46,000× worse than NumPy on a bog-standard `sum`, and `mean`, `std`, `var` and every statistic * inherit that error. * * @packageDocumentation */ /** * Sum with **pairwise (cascade) summation** — the algorithm behind `np.sum`. * * Naive accumulation lets the running total grow large while the addends stay small, so each * addition rounds off a little more of the total: error grows as **O(n)·ε**. Pairwise summation * adds numbers of *comparable magnitude* by recursively halving the range, so error grows as * **O(log n)·ε** — for n = 10⁶ that is the difference between ~1e-11 and ~1e-16. * * It costs the same number of additions as the naive loop. There is no speed/accuracy trade here; * the naive version is simply worse. * * Not exact: for that, use {@link neumaierSum}. Pairwise is the right default because it is free. */ declare function pairwiseSum(xs: ArrayLike, start?: number, end?: number): number; /** * Sum with **Neumaier compensation** — correctly rounded for practical purposes, the equivalent * of Python's `math.fsum`. * * Tracks the low-order bits that each addition throws away and folds them back in at the end. It * recovers information that pairwise summation cannot: `[1e16, 1, -1e16]` sums to **1** here, * while both naive and pairwise (and `np.sum`) give **0**, because the `1` is annihilated the * moment it meets `1e16`. * * ~2-4× slower than {@link pairwiseSum}, so it is opt-in rather than the default. Reach for it * when catastrophic cancellation is possible: near-zero results from large terms, long-running * accumulators, conservation checks. * * (Neumaier's variant, not classic Kahan: Kahan loses the compensation when the *addend* is * larger than the running sum, which is precisely the `1e16` case.) */ declare function neumaierSum(xs: ArrayLike): number; /** * Euclidean (2-)norm that does **not** overflow or underflow — BLAS's `dnrm2` scaling. * * The obvious `sqrt(Σxᵢ²)` squares before it adds, so it dies well inside the representable * range: `‖[1e200, 1e200, 1e200, 1e200]‖` overflows to `Infinity` (the true answer, 2e200, is * perfectly representable), and `‖[1e-200] × 4‖` **flushes to 0** — a silent wrong answer, which * is worse. * * NumPy has this bug too: `np.linalg.norm([1e200]*4)` returns `inf` with an overflow warning. * LAPACK does not, and neither do we. * * The fix is to carry a running scale: keep the largest magnitude seen out of the sum of squares, * so the accumulator only ever holds ratios in [0, 1]. */ declare function norm2(xs: ArrayLike): number; /** * Dot product `Σ aᵢ·bᵢ` with **pairwise (cascade) summation** of the products — the accuracy of * {@link pairwiseSum} applied to a dot without materialising the product array. * * A naive `s += a[i]*b[i]` loop carries the same **O(n)·ε** error as a naive sum; measured against * an exact reference on an ill-conditioned dot (large mean × small factor, n = 10⁶) it is ~18× * worse than `np.dot`, which sums pairwise. This closes that gap — and, like {@link pairwiseSum}, * costs the same number of flops as the naive loop. * * The two ranges are assumed the same length; callers guard that. Reads only `[start, end)`. */ declare function pairwiseDot(a: ArrayLike, b: ArrayLike, start?: number, end?: number): number; /** * Euclidean distance `‖a − b‖₂` that does **not** overflow or underflow — {@link norm2}'s BLAS * `dnrm2` scaling applied to the elementwise difference. * * `distance` is just a 2-norm, so the obvious `sqrt(Σ(aᵢ−bᵢ)²)` inherits norm's pathology: it * squares before it adds, overflowing to `Infinity` and — the dangerous case — **flushing to a * silent 0** for small differences well inside the representable range. NumPy's `linalg.norm` has * the same bug; scaling on the largest *difference* seen avoids both. The scale tracks the residual * `a − b`, not the inputs, so it stays accurate even when `a` and `b` are individually huge. * * The two ranges are assumed the same length; callers guard that. */ declare function scaledDistance(a: ArrayLike, b: ArrayLike): number; /** * Sum of squared deviations from the mean, `Σ(xᵢ − x̄)²` — the **corrected two-pass** form, the * numerator of a numerically stable variance. * * Variance is where large means bite: the deviations `xᵢ − x̄` can be O(1) while the values sit on * a huge pedestal, so any error in `x̄` rides straight into every deviation. Two things fix it: * 1. compute the mean with {@link pairwiseSum}, not a naive running total; and * 2. subtract the residual mean-bias term `(Σd)²/n` — `Σd` is zero in exact arithmetic but not in * floating point, and that leftover is exactly the systematic error a plain `Σd²` carries. * * Measured on 1e9-pedestal data: the plain naive two-pass (what shipped) lands ~1e-7 relative error; * this lands ~1e-16 — better than `np.var`, which uses the uncorrected two-pass (~1e-13). * * Divide the result by `n` (uncorrected), `n − 1` (unbiased/sample), or `n + 1` (biased) for the * corresponding variance. Returns 0 for fewer than two elements. */ declare function sumSquaredDeviations(xs: ArrayLike): number; /** * Cumulative sum with **Neumaier compensation** — each prefix total is written to `out[i]` carrying * the low-order bits a naive running sum throws away. * * A cumulative sum is an inherently sequential prefix scan, so pairwise summation does not apply: * you need every intermediate total, not just the final one. `np.cumsum` therefore accumulates * naively and its tail drifts by **O(n)·ε** (relErr ~1.3e-11 over 10⁶ terms). Carrying a running * compensation costs a few extra flops per element, no extra memory, and makes every prefix exact * for practical purposes — a strict improvement over NumPy where accumulated drift matters (e.g. * integrating a signal). * * Writes `out[i]` for `i` in `[0, xs.length)`; `out` may be a `number[]` or a `Float64Array`. */ declare function neumaierCumsum(xs: ArrayLike, out: { [index: number]: number; }): void; /** * @danielsimonjr/mathts-core - Core types and utilities for MathTS * @packageDocumentation */ declare const VERSION: string; export { ALL_UNITS, BASE_UNITS, BEST_PREFIXES, BIGNUMBER_E, BIGNUMBER_LN10, BIGNUMBER_LN2, BIGNUMBER_NEG_ONE, BIGNUMBER_ONE, BIGNUMBER_PI, BIGNUMBER_TEN, BIGNUMBER_ZERO, type BackendType, BigNumber, type BigNumberConfig, COMPLEX_NEG_ONE, COMPLEX_ONE, COMPLEX_ZERO, Complex, type ConversionDef, DEFAULT_CONFIG, DERIVED_UNITS, DIMENSIONLESS, DUAL_UNARY_RULES, DimensionMismatchError, type Dimensions, Dual, type DualUnaryRule, type DualUnaryRuleName, E, FRACTION_HALF, FRACTION_NEG_ONE, FRACTION_ONE, FRACTION_QUARTER, FRACTION_THIRD, FRACTION_ZERO, type FactoryDependencies, type FactoryFunction, type FactoryImport, Fraction, FunctionRegistry, I, type IBigNumber, type IComplex, type IFraction, type IMatrix, LN10, LN2, LOG10E, LOG2E, MATHTS_CONVERSIONS, MATHTS_TYPES, type MathTSConfig, type MathTSValue, type MatrixBackend, type MatrixDimensions, type NumericScalar, type NumericType, PHI, PI, Range, type RangeForEachCallback, type RangeFormatOptions, type RangeJSON, type RangeMapCallback, type RoundingMode, SI_PREFIXES, SQRT1_2, SQRT2, type Scalar, TAU, type TypeDef, TypeRegistry, UNIT_ALIASES, type UnitDef, UnitParseError, VERSION, abs, addScalar, createFactory, createMathTSTyped, createRangeClass, createTypedFunction, dim, divideScalar, equal, fix, getPrefix, getUnitDef, initTypedWasm, isArray, isBigInt, isBigNumber, isBoolean, isComplex, isDenseMatrix, isDual, isFraction, isFunction, isMatrix, isNull, isNumber, isNumeric, isObject, isSparseMatrix, isString, isTypedWasmAvailable, isUndefined, isUnit, math, mathTyped, multiplyScalar, neumaierCumsum, neumaierSum, norm2, number, pairwiseDot, pairwiseSum, pow, registerNativeTypes, registry, round, scaledDistance, subtractScalar, sumSquaredDeviations };