1.0.2 • Published 5 months ago

kimath v1.0.2

Weekly downloads
-
License
MIT
Repository
-
Last release
5 months ago

KiMath: Ultimate Quantum Adaptive Math Library (2025+ Edition)

License: MIT

KiMath is a next‑generation, adaptive math library for JavaScript designed to push the limits of performance and flexibility. It leverages modern techniques such as multi‑threading (via Worker Threads in Node.js and Web Workers in browsers), WebAssembly (WASM) stubs, and quantum‑inspired algorithms to deliver hundreds of high‑performance math functions—all accessible through a unified, intuitive API. KiMath works seamlessly in Node.js (v20+) and modern browsers.


Table of Contents


Features

Adaptive Performance:
KiMath dynamically selects the best implementation (pure JavaScript, WASM, or multi‑threaded) based on your runtime environment.

Comprehensive Math Functions:
KiMath provides hundreds of functions covering arithmetic, trigonometry, calculus, linear algebra, number theory, statistics, geometry, finance, physics, machine learning, and more.

Quantum-Inspired Computation:
Offload heavy computations to a worker pool for parallel processing.

Unified DSL:
Evaluate mathematical expressions using a natural-language–like syntax.

Plugin Architecture:
Easily extend KiMath with your own modules and functions.

Cross-Platform:
Works seamlessly in both Node.js (v20+) and modern browsers.

Built-In Performance Dashboard:
(Stub) Monitor key performance metrics and auto‑tuning status.


Overview

KiMath isn’t just a library of functions—it’s a complete mathematical ecosystem. Its design philosophy centers on:

Speed & Efficiency:
Utilizing techniques like memoization, parallel computation (via Worker Threads/Web Workers), and placeholders for future WebAssembly and GPU acceleration.

Developer Friendliness:
An intuitive API and unified DSL that let you write math expressions in a clear, natural way.

Extensibility:
A built‑in plugin system that lets you add your own modules without modifying the core library.

Installation

Using npm

Install KiMath from npm:

npm install kimath

Then import it in your project:

const KiMath = require('kimath');

Manual Download

Download the kimath.js file and include it in your project.

  • For the Browser:
    Add a <script> tag:

    <script src="path/to/kimath.js"></script>
    <script>
      console.log(KiMath.add(2, 3)); // 5
    </script>
  • For Node.js:
    Require it in your code:

    const KiMath = require('./kimath.js');

Usage

Basic Examples

console.log(KiMath.add(2, 3));         // 5
console.log(KiMath.sqrt(16));          // 4
console.log(KiMath.sin(Math.PI / 2));    // 1
console.log(KiMath.factorial(5));        // 120
console.log(KiMath.fibonacci(10));       // 55

Advanced Examples

Using the DSL for Expression Computation

const result = KiMath.compute("2*x + 3", { x: 4 });
console.log(result); // 11

Offloading Computations with Quantum Compute

KiMath.quantumCompute("fastSqrt", 256)
  .then(result => {
    console.log("Quantum compute fastSqrt(256):", result);
  })
  .catch(error => console.error(error));

Extending with Plugins

KiMath.registerPlugin("samplePlugin", {
  hello: () => "Hello from plugin!"
});
console.log(KiMath.hello()); // "Hello from plugin!"

Displaying the Performance Dashboard

KiMath.showPerformanceDashboard();

API Documentation

1. Basic Arithmetic & Number Functions

  • add(a, b): Returns the sum of two numbers.
  • sub(a, b): Returns the difference.
  • mul(a, b): Returns the product.
  • div(a, b): Returns the quotient (throws on division by zero).
  • mod(a, b): Returns the positive modulus.
  • abs(x), sqrt(x), cbrt(x), pow(x, y), exp(x), log(x), log10(x), log2(x): Standard functions.
  • ceil(x), floor(x), round(x), trunc(x): Rounding functions.
  • clamp(x, min, max): Clamps a value between min and max.
  • lerp(a, b, t): Linear interpolation.
  • sumArray(arr), prodArray(arr), avgArray(arr), minArray(arr), maxArray(arr): Array utilities.
  • factorial(n): Memoized factorial function.
  • fibonacci(n): Returns the nth Fibonacci number.
  • gcd(a, b), lcm(a, b): Greatest common divisor and least common multiple.
  • powerN(x): Auto-generated power functions (e.g., power2, power3, …, up to power50).
  • rootN(x): Auto-generated nth root functions (e.g., root2, root3, …, up to root50).

2. Trigonometry & Hyperbolic Functions

  • sin(x), cos(x), tan(x), asin(x), acos(x), atan(x), atan2(y, x): Standard trigonometric functions.
  • sec(x), csc(x), cot(x): Reciprocal functions.
  • sinh(x), cosh(x), tanh(x), asinh(x), acosh(x), atanh(x): Hyperbolic functions.
  • degToRad(deg), radToDeg(rad): Conversions between degrees and radians.
  • sinDeg(deg), cosDeg(deg), tanDeg(deg): Trigonometric functions that accept degrees.

3. Calculus: Derivatives, Integrals & Series

  • derivative(f, x, h): Approximates the derivative of function f at x.
  • secondDerivative(f, x, h): Approximates the second derivative.
  • integral(f, a, b, n): Numerical integration using a Riemann sum.
  • integralSimpson(f, a, b, n): Simpson’s rule integration.
  • taylorSeries(f, x, n): Taylor series approximation of f at x.

4. Linear Algebra & Matrix Operations

  • matrixAdd(A, B), matrixSub(A, B): Matrix addition and subtraction.
  • matrixMul(A, B): Matrix multiplication.
  • matrixTranspose(M): Transpose of a matrix.
  • matrixDeterminant(M): Recursively computes the determinant.
  • matrixInverse2x2(M): Inverse of a 2×2 matrix.
  • dotProduct(v1, v2), crossProduct(v1, v2): Vector dot and cross products.
  • vectorNorm(v), vectorDistance(v1, v2): Euclidean norm and distance.

5. Number Theory & Combinatorics

  • isPrime(n): Returns true if n is prime.
  • nextPrime(n): Returns the next prime after n.
  • primeFactors(n): Returns an array of prime factors.
  • totient(n): Euler’s Totient function.
  • sumDivisors(n): Sum of all divisors of n.
  • isPerfect(n): Checks if n is a perfect number.
  • modExp(base, exp, mod): Modular exponentiation.
  • modInverse(a, m): Modular multiplicative inverse.
  • permutations(n, r), combinations(n, r), binomialCoefficient(n, r): Combinatorial functions.
  • catalan(n): Returns the nth Catalan number.
  • derangements(n): Number of derangements for n objects.

6. Statistics & Probability

  • mean(arr), median(arr), mode(arr): Basic descriptive statistics.
  • variance(arr), stdDev(arr): Population variance and standard deviation.
  • sampleVariance(arr), sampleStdDev(arr): Sample variance and standard deviation.
  • skewness(arr), kurtosis(arr): Measures of distribution shape.
  • percentile(arr, p), quartiles(arr), interquartileRange(arr): Percentile and quartile calculations.
  • covariance(arr1, arr2), correlation(arr1, arr2): Covariance and correlation between arrays.
  • normalPDF(x, mean, std), normalCDF(x, mean, std): Normal distribution functions.
  • poissonPDF(lambda, k), exponentialPDF(x, lambda): Other probability density functions.

7. Geometry

  • areaCircle(r), circumferenceCircle(r): Circle properties.
  • areaEllipse(a, b), circumferenceEllipse(a, b): Ellipse calculations.
  • areaTriangle(a, b, c), areaTriangleBaseHeight(base, height): Triangle areas.
  • areaRectangle(l, w), perimeterRectangle(l, w): Rectangle calculations.
  • areaSquare(s), perimeterSquare(s): Square metrics.
  • areaParallelogram(base, height), areaTrapezoid(a, b, h): Other shape areas.
  • areaRegularPolygon(n, s): Area of a regular polygon; auto‑generated variants exist for n = 3–20.
  • perimeterPolygon(n, s): Perimeter of a polygon.
  • volumeSphere(r), volumeCylinder(r, h), volumeCone(r, h), volumeCube(s), volumeRectPrism(l, w, h): Volumes of various solids.
  • surfaceAreaSphere(r), surfaceAreaCylinder(r, h), surfaceAreaCone(r, l), surfaceAreaCube(s): Surface areas.
  • distance2D(x1, y1, x2, y2), distance3D(x1, y1, z1, x2, y2, z2): Distance formulas.

8. Finance & Economics

  • compoundInterest(P, r, t, n): Compound interest calculation.
  • futureValue(PV, r, t), presentValue(FV, r, t): Time value of money.
  • annuityPayment(PV, r, n), mortgagePayment(P, r, n): Loan and annuity calculations.
  • netPresentValue(cashFlows, r), internalRateOfReturn(cashFlows, guess, iterations): Investment metrics.
  • depreciationStraightLine(cost, salvage, life), depreciationDecliningBalance(cost, rate, period): Depreciation calculations.
  • roi(gain, cost): Return on investment.

9. Physics & Engineering

  • kineticEnergy(m, v), potentialEnergy(m, g, h): Energy computations.
  • momentum(m, v), force(m, a): Mechanics.
  • power(work, t), workDone(F, d): Work and power calculations.
  • pressure(F, A), density(mass, volume): Physical properties.
  • acceleration(v0, v, t): Acceleration.
  • gravitationalForce(m1, m2, d): Newton’s law of gravitation.
  • impulse(F, t): Impulse.
  • ohmsLaw(V, I): Electrical resistance.
  • idealGasLaw(n, R, T, V): Gas properties.

10. Machine Learning & AI Functions

  • Activation Functions:
    sigmoid(x), tanh(x), relu(x), leakyRelu(x, alpha), softplus(x), swish(x).
  • Loss Functions:
    mseLoss(pred, actual), maeLoss(pred, actual), crossEntropyLoss(pred, actual).

11. Utility & Conversion Functions

  • Random Number Generators:
    random(min, max), randomInt(min, max).
  • Array Utilities:
    shuffleArray(arr), rangeArray(start, end, step), uniqueArray(arr).
  • Unit Conversions:
    celsiusToFahrenheit(C), fahrenheitToCelsius(F), kmToMiles(km), milesToKm(miles), kgToPounds(kg), poundsToKg(lb).

12. Advanced Features

  • DSL:
    compute(expression, variables) to evaluate mathematical expressions written as strings.
  • Optimization Mode:
    setOptimizationMode(mode) (stub) to change performance modes (e.g., "WASM", "GPU").
  • Plugin System:
    registerPlugin(pluginName, pluginObject) to extend KiMath with additional functions.
  • Performance Dashboard:
    showPerformanceDashboard() displays performance metrics (stub).
  • Quantum Compute:
    quantumCompute(funcName, ...args) offloads heavy computation to a worker pool.

Contributing

Contributions are welcome! To contribute to KiMath:

  1. Fork the Repository: Create your own branch for your changes.
  2. Write Tests: Ensure your changes are covered by tests.
  3. Update Documentation: Update the README and any relevant docs.
  4. Submit a Pull Request: Explain your changes in detail.


License

KiMath is licensed under the MIT License. See the LICENSE file for details.


Acknowledgements

KiMath is inspired by state‑of‑the‑art mathematical libraries and cutting‑edge research in computational science. Special thanks to the open‑source community for their support and inspiration.


Most of the cases it is very fast 
the more bottom line is more fast !!

40.61 ┼╮
36.55 ┤│
32.50 ┤╰╮     ╭╮ ╭╮   ╭╮
28.44 ┤ ╰=====================
24.38 ┤
20.33 ┤
16.27 ┤
12.22 ┤
8.16  ┤
4.10  ┼╮
0.05  ┤╰──────────────────



 (====) = other math libs, (───) = KiMath