├── adv-math ├── src │ ├── constants.js │ ├── expression-parsing │ │ └── parser.js │ ├── basic │ │ ├── arithmetic.js │ │ └── complex.js │ ├── random │ │ └── random.js │ ├── calculus │ │ └── calculus.js │ ├── bitwise │ │ └── bitwise.js │ ├── index.js │ ├── statistics │ │ └── statistics.js │ ├── units-conversions │ │ └── units.js │ ├── linear-algebra │ │ ├── vector.js │ │ └── matrix.js │ ├── equation-solvers │ │ └── equations.js │ ├── financial │ │ └── financial.js │ ├── geometry-trigonometry │ │ ├── geometry.js │ │ └── trigonometry.js │ └── expression-evaluator │ │ └── expression-evaluator.js ├── .gitignore ├── tests │ ├── expression-parsing.test.js │ ├── bitwise.test.js │ ├── calculus.test.js │ ├── index.test.js │ ├── equation-solvers.test.js │ ├── random.test.js │ ├── financial.test.js │ ├── statistics.test.js │ ├── basic.test.js │ ├── units-conversions.test.js │ ├── expression-evaluator.test.js │ ├── linear-algebra.test.js │ └── geometry-trigonometry.test.js ├── docs │ ├── Parser.md │ ├── Constants.md │ ├── Random.md │ ├── Equations.md │ ├── Statistics.md │ ├── Units.md │ ├── Vector.md │ ├── BasicMath.md │ ├── Geometry.md │ ├── Matrix.md │ ├── Financial.md │ ├── Calculus.md │ ├── ExpressionEvaluator.md │ ├── Index.md │ ├── ComplexNumber.md │ └── Trigonometry.md ├── package.json └── README.md ├── LICENSE ├── STRUCTURE.md ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LEARN.md └── README.md /adv-math/src/constants.js: -------------------------------------------------------------------------------- 1 | class Constants { 2 | // Define mathematical constants 3 | static PI = Math.PI; 4 | static E = Math.E; 5 | static GOLDEN_RATIO = (1 + Math.sqrt(5)) / 2; 6 | static SQUARE_ROOT_2 = Math.sqrt(2); 7 | static SQUARE_ROOT_3 = Math.sqrt(3); 8 | // Add more constants as needed 9 | } 10 | 11 | module.exports = Constants; 12 | -------------------------------------------------------------------------------- /adv-math/.gitignore: -------------------------------------------------------------------------------- 1 | # Node.js / npm 2 | node_modules/ 3 | npm-debug.log 4 | 5 | # Dependency directories 6 | yarn-error.log 7 | .pnp 8 | .pnp.js 9 | 10 | # Optional eslint cache 11 | .eslintcache 12 | 13 | # Optional stylelint cache 14 | .stylelintcache 15 | 16 | # Mac OS 17 | .DS_Store 18 | 19 | # JetBrains IDEs 20 | .idea/ 21 | 22 | # Visual Studio Code 23 | .vscode/ 24 | 25 | # Cache of JetBrains IDEs 26 | .caches/ -------------------------------------------------------------------------------- /adv-math/src/expression-parsing/parser.js: -------------------------------------------------------------------------------- 1 | class Parser { 2 | // Method to evaluate a mathematical expression 3 | static evaluate(expression) { 4 | try { 5 | // Use the built-in JavaScript eval function to evaluate the expression 6 | return eval(expression); 7 | } catch (error) { 8 | throw new Error('Invalid expression.'); 9 | } 10 | } 11 | } 12 | 13 | module.exports = Parser; 14 | -------------------------------------------------------------------------------- /adv-math/src/basic/arithmetic.js: -------------------------------------------------------------------------------- 1 | class BasicMath { 2 | static add(a, b) { 3 | return a + b; 4 | } 5 | 6 | static subtract(a, b) { 7 | return a - b; 8 | } 9 | 10 | static multiply(a, b) { 11 | return a * b; 12 | } 13 | 14 | static divide(a, b) { 15 | if (b === 0) { 16 | throw new Error('Division by zero is not allowed.'); 17 | } 18 | return a / b; 19 | } 20 | } 21 | 22 | module.exports = BasicMath; -------------------------------------------------------------------------------- /adv-math/tests/expression-parsing.test.js: -------------------------------------------------------------------------------- 1 | const Parser = require('../src/expression-parsing/parser'); 2 | 3 | describe('Parser', () => { 4 | test('evaluates a simple mathematical expression', () => { 5 | expect(Parser.evaluate('2 + 3')).toBe(5); 6 | }); 7 | 8 | test('evaluates a complex mathematical expression', () => { 9 | expect(Parser.evaluate('2 * (3 + 4)')).toBe(14); 10 | }); 11 | 12 | test('throws an error for an invalid expression', () => { 13 | expect(() => { 14 | Parser.evaluate('2 +'); 15 | }).toThrow('Invalid expression.'); 16 | }); 17 | 18 | // Add more test cases as needed 19 | }); 20 | -------------------------------------------------------------------------------- /adv-math/src/random/random.js: -------------------------------------------------------------------------------- 1 | class Random { 2 | // Method to generate a random integer between min (inclusive) and max (exclusive) 3 | static generateRandomInt(min, max) { 4 | if (max <= min) { 5 | throw new Error('Invalid range for generating random integer.'); 6 | } 7 | return Math.floor(Math.random() * (max - min)) + min; 8 | } 9 | 10 | // Method to generate a random float between min (inclusive) and max (exclusive) 11 | static generateRandomFloat(min, max) { 12 | if (max <= min) { 13 | throw new Error('Invalid range for generating random float.'); 14 | } 15 | return Math.random() * (max - min) + min; 16 | } 17 | } 18 | 19 | module.exports = Random; 20 | -------------------------------------------------------------------------------- /adv-math/src/calculus/calculus.js: -------------------------------------------------------------------------------- 1 | class Calculus { 2 | // Method to calculate the derivative of a function at a given point using numerical differentiation (finite difference method) 3 | static derivative(func, point, h = 0.001) { 4 | const f_x = func(point); 5 | const f_x_plus_h = func(point + h); 6 | 7 | return (f_x_plus_h - f_x) / h; 8 | } 9 | 10 | // Method to calculate the definite integral of a function between two points using numerical integration (trapezoidal rule) 11 | static integral(func, a, b, n = 1000) { 12 | const h = (b - a) / n; 13 | let sum = (func(a) + func(b)) / 2; 14 | 15 | for (let i = 1; i < n; i++) { 16 | const x_i = a + i * h; 17 | sum += func(x_i); 18 | } 19 | 20 | return sum * h; 21 | } 22 | } 23 | 24 | module.exports = Calculus; 25 | -------------------------------------------------------------------------------- /adv-math/tests/bitwise.test.js: -------------------------------------------------------------------------------- 1 | const BitWise = require("../src/bitwise/bitwise"); 2 | 3 | describe("BitWiseMath", () => { 4 | test("count set bits", () => { 5 | expect(BitWise.countSetBits(8)).toBe(1); 6 | }); 7 | 8 | test("check ith bit", () => { 9 | expect(BitWise.checkIthBit(8, 2)).toBe(0); 10 | }); 11 | 12 | test("toogle ith bit", () => { 13 | expect(BitWise.toggleBitAtPosition(4, 1)).toBe(6); 14 | }); 15 | 16 | test("check is power of 2", () => { 17 | expect(BitWise.isPowerOfTwo(4)).toBe(true); 18 | }); 19 | 20 | test("check is power of 2", () => { 21 | expect(BitWise.isPowerOfTwo(6)).toBe(false); 22 | }); 23 | test("find hamming distance", () => { 24 | expect(BitWise.hammingDistance(7, 4)).toBe(2); 25 | }); 26 | test("find hamming distance", () => { 27 | expect(BitWise.hammingDistance(9, 14)).toBe(3); 28 | }); 29 | }); 30 | -------------------------------------------------------------------------------- /adv-math/tests/calculus.test.js: -------------------------------------------------------------------------------- 1 | const Calculus = require('../src/calculus/calculus'); 2 | 3 | describe('Calculus', () => { 4 | test('calculates the derivative of a function at a point', () => { 5 | // Define a sample function (e.g., f(x) = x^2) 6 | const func = (x) => x * x; 7 | 8 | // Calculate the derivative at x = 2 9 | const derivative = Calculus.derivative(func, 2); 10 | expect(derivative).toBeCloseTo(4, 2); 11 | }); 12 | 13 | test('calculates the definite integral of a function between two points', () => { 14 | // Define a sample function (e.g., f(x) = x^2) 15 | const func = (x) => x * x; 16 | 17 | // Calculate the integral of the function from 1 to 3 18 | const integral = Calculus.integral(func, 1, 3); 19 | expect(integral).toBeCloseTo(8.67, 2); 20 | }); 21 | 22 | // Add more test cases as needed 23 | }); 24 | -------------------------------------------------------------------------------- /adv-math/tests/index.test.js: -------------------------------------------------------------------------------- 1 | const advMath = require('../src/index'); 2 | 3 | describe('adv-math', () => { 4 | test('exports BasicMath module', () => { 5 | expect(advMath.BasicMath).toBeDefined(); 6 | expect(typeof advMath.BasicMath.add).toBe('function'); 7 | // Add more tests for BasicMath methods as needed 8 | }); 9 | 10 | test('exports ComplexNumber module', () => { 11 | expect(advMath.ComplexNumber).toBeDefined(); 12 | expect(typeof advMath.ComplexNumber.add).toBe('undefined'); 13 | // Add more tests for ComplexNumber methods as needed 14 | }); 15 | 16 | // Repeat similar tests for other exported modules 17 | 18 | test('exports Constants module', () => { 19 | expect(advMath.Constants).toBeDefined(); 20 | expect(advMath.Constants.PI).toBe(Math.PI); 21 | expect(advMath.Constants.E).toBe(Math.E); 22 | // Add more tests for Constants properties as needed 23 | }); 24 | }); -------------------------------------------------------------------------------- /adv-math/src/bitwise/bitwise.js: -------------------------------------------------------------------------------- 1 | class Bitwise { 2 | static hammingDistance(firstNumber, secondNumber) { 3 | let xor = firstNumber ^ secondNumber; 4 | let distance = 0; 5 | while (xor > 0) { 6 | distance += xor & 1; 7 | xor >>= 1; 8 | } 9 | return distance; 10 | } 11 | 12 | static countSetBits(n) { 13 | let setBitCount = 0; 14 | while (n) { 15 | n = n & (n - 1); 16 | setBitCount++; 17 | } 18 | return setBitCount; 19 | } 20 | 21 | static checkIthBit(number, position) { 22 | if (number & (1 << position)) { 23 | return 1; 24 | } 25 | return 0; 26 | } 27 | 28 | static toggleBitAtPosition(number, position) { 29 | number = number ^ (1 << position); 30 | return number; 31 | } 32 | 33 | static isPowerOfTwo(number) { 34 | if (typeof number !== "number") { 35 | return "enter a valid number"; 36 | } 37 | return (number & (number - 1)) === 0; 38 | } 39 | 40 | } 41 | 42 | module.exports = Bitwise; 43 | -------------------------------------------------------------------------------- /adv-math/tests/equation-solvers.test.js: -------------------------------------------------------------------------------- 1 | const Equations = require('../src/equation-solvers/equations'); 2 | 3 | describe('Equations', () => { 4 | test('solves a linear equation', () => { 5 | expect(Equations.solveLinear(2, -3)).toBe(1.5); 6 | }); 7 | 8 | test('solves a quadratic equation with real roots', () => { 9 | const solutions = Equations.solveQuadratic(1, -3, 2); 10 | expect(solutions).toContainEqual(2); 11 | expect(solutions).toContainEqual(1); 12 | }); 13 | 14 | test('throws an error for a linear equation with zero coefficient', () => { 15 | expect(() => { 16 | Equations.solveLinear(0, -3); 17 | }).toThrow('The coefficient of x cannot be zero.'); 18 | }); 19 | 20 | test('throws an error for a quadratic equation with no real roots', () => { 21 | expect(() => { 22 | Equations.solveQuadratic(1, 2, 5); 23 | }).toThrow('The equation has no real roots.'); 24 | }); 25 | 26 | // Add more test cases as needed 27 | }); 28 | -------------------------------------------------------------------------------- /adv-math/src/basic/complex.js: -------------------------------------------------------------------------------- 1 | class ComplexNumber { 2 | constructor(real, imaginary) { 3 | this.real = real; 4 | this.imaginary = imaginary; 5 | } 6 | 7 | // Method to add two complex numbers 8 | add(complex) { 9 | return new ComplexNumber(this.real + complex.real, this.imaginary + complex.imaginary); 10 | } 11 | 12 | // Method to subtract two complex numbers 13 | subtract(complex) { 14 | return new ComplexNumber(this.real - complex.real, this.imaginary - complex.imaginary); 15 | } 16 | 17 | // Method to multiply two complex numbers 18 | multiply(complex) { 19 | const realPart = this.real * complex.real - this.imaginary * complex.imaginary; 20 | const imaginaryPart = this.real * complex.imaginary + this.imaginary * complex.real; 21 | return new ComplexNumber(realPart, imaginaryPart); 22 | } 23 | 24 | // Method to get the magnitude (absolute value) of a complex number 25 | magnitude() { 26 | return Math.sqrt(this.real * this.real + this.imaginary * this.imaginary); 27 | } 28 | } 29 | 30 | module.exports = ComplexNumber; 31 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Pabitra Banerjee 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /adv-math/tests/random.test.js: -------------------------------------------------------------------------------- 1 | const Random = require('../src/random/random'); 2 | 3 | describe('Random', () => { 4 | test('generates a random integer within a specified range', () => { 5 | const randomInt = Random.generateRandomInt(1, 10); 6 | expect(randomInt).toBeGreaterThanOrEqual(1); 7 | expect(randomInt).toBeLessThan(10); 8 | }); 9 | 10 | test('generates a random float within a specified range', () => { 11 | const randomFloat = Random.generateRandomFloat(0, 1); 12 | expect(randomFloat).toBeGreaterThanOrEqual(0); 13 | expect(randomFloat).toBeLessThan(1); 14 | }); 15 | 16 | test('throws an error for an invalid integer range', () => { 17 | expect(() => { 18 | Random.generateRandomInt(10, 1); 19 | }).toThrow('Invalid range for generating random integer.'); 20 | }); 21 | 22 | test('throws an error for an invalid float range', () => { 23 | expect(() => { 24 | Random.generateRandomFloat(1, 1); 25 | }).toThrow('Invalid range for generating random float.'); 26 | }); 27 | 28 | // Add more test cases as needed 29 | }); 30 | -------------------------------------------------------------------------------- /adv-math/tests/financial.test.js: -------------------------------------------------------------------------------- 1 | const Financial = require('../src/financial/financial'); 2 | 3 | describe('Financial', () => { 4 | test('calculates the future value of an investment', () => { 5 | const principal = 1000; 6 | const rate = 0.05; 7 | const time = 5; 8 | const futureValue = Financial.futureValue(principal, rate, time); 9 | expect(futureValue).toBeCloseTo(1276.28, 2); 10 | }); 11 | 12 | test('calculates the compound interest earned on an investment', () => { 13 | const principal = 1000; 14 | const rate = 0.05; 15 | const time = 5; 16 | const compoundInterest = Financial.compoundInterest(principal, rate, time); 17 | expect(compoundInterest).toBeCloseTo(276.28, 2); 18 | }); 19 | 20 | test('calculates the present value of a future amount', () => { 21 | const futureValue = 1270.63; 22 | const rate = 0.05; 23 | const time = 5; 24 | const presentValue = Financial.presentValue(futureValue, rate, time); 25 | expect(presentValue).toBeCloseTo(995.57, 2); 26 | }); 27 | 28 | // Add more test cases as needed 29 | }); 30 | -------------------------------------------------------------------------------- /adv-math/tests/statistics.test.js: -------------------------------------------------------------------------------- 1 | const Statistics = require('../src/statistics/statistics'); 2 | 3 | describe('Statistics', () => { 4 | test('calculates the mean of an array', () => { 5 | const numbers = [1, 2, 3, 4, 5]; 6 | expect(Statistics.mean(numbers)).toBe(3); 7 | }); 8 | 9 | test('calculates the median of an odd-length array', () => { 10 | const numbers = [4, 1, 3]; 11 | expect(Statistics.median(numbers)).toBe(3); 12 | }); 13 | 14 | test('calculates the median of an even-length array', () => { 15 | const numbers = [4, 1, 3, 2]; 16 | expect(Statistics.median(numbers)).toBe(2.5); 17 | }); 18 | 19 | test('calculates the standard deviation of an array', () => { 20 | const numbers = [2, 4, 4, 4, 5, 5, 7, 9]; 21 | expect(Statistics.standardDeviation(numbers)).toBeCloseTo(2.138, 3); 22 | }); 23 | 24 | test('throws an error for an empty array in mean calculation', () => { 25 | const numbers = []; 26 | expect(() => { 27 | Statistics.mean(numbers); 28 | }).toThrow('Array must not be empty.'); 29 | }); 30 | 31 | // Add more test cases as needed 32 | }); -------------------------------------------------------------------------------- /adv-math/src/index.js: -------------------------------------------------------------------------------- 1 | const BasicMath = require('./basic/arithmetic'); 2 | const ComplexNumber = require('./basic/complex'); 3 | const Matrix = require('./linear-algebra/matrix'); 4 | const Vector = require('./linear-algebra/vector'); 5 | const Statistics = require('./statistics/statistics'); 6 | const Geometry = require('./geometry-trigonometry/geometry'); 7 | const Trigonometry = require('./geometry-trigonometry/trigonometry'); 8 | const Calculus = require('./calculus/calculus'); 9 | const Financial = require('./financial/financial'); 10 | const Units = require('./units-conversions/units'); 11 | const Equations = require('./equation-solvers/equations'); 12 | const Parser = require('./expression-parsing/parser'); 13 | const Random = require('./random/random'); 14 | const Constants = require('./constants'); 15 | const ExpressionEvaluator = require('./expression-evaluator/expression-evaluator'); 16 | 17 | module.exports = { 18 | BasicMath, 19 | ComplexNumber, 20 | Matrix, 21 | Vector, 22 | Statistics, 23 | Geometry, 24 | Trigonometry, 25 | Calculus, 26 | Financial, 27 | Units, 28 | Equations, 29 | Parser, 30 | Random, 31 | Constants, 32 | ExpressionEvaluator, 33 | // Add other modules here 34 | }; -------------------------------------------------------------------------------- /adv-math/docs/Parser.md: -------------------------------------------------------------------------------- 1 | # Parser Module 2 | 3 | The `Parser` module provides a method for evaluating mathematical expressions in JavaScript. 4 | 5 | ## Usage 6 | 7 | To use the `Parser` module, import it and use its `evaluate` method in your JavaScript code. 8 | 9 | ```javascript 10 | const Parser = require('adv-math').Parser; 11 | 12 | // Example usage 13 | const expression = "2 + 3 * 4"; 14 | const result = Parser.evaluate(expression); // Evaluate the expression 15 | ``` 16 | 17 | ## Methods 18 | 19 | ### `evaluate(expression)` 20 | 21 | Evaluates a mathematical expression. 22 | 23 | - `expression` (string): The mathematical expression to evaluate. 24 | - Returns: The result of evaluating the expression. 25 | 26 | If the expression is invalid or cannot be evaluated, an error is thrown with the message "Invalid expression." 27 | 28 | ## Examples 29 | 30 | ```javascript 31 | const Parser = require('adv-math').Parser; 32 | 33 | // Example expression: 2 + 3 * 4 34 | const expression = "2 + 3 * 4"; 35 | const result = Parser.evaluate(expression); // Returns 14 36 | 37 | // Example expression with an error: "2 + 3 *" 38 | try { 39 | const invalidExpression = "2 + 3 *"; 40 | const invalidResult = Parser.evaluate(invalidExpression); // Throws an error 41 | } catch (error) { 42 | console.error(error.message); // Outputs "Invalid expression." 43 | } 44 | ``` 45 | -------------------------------------------------------------------------------- /adv-math/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "adv-math", 3 | "description": "adv-math is a comprehensive JavaScript library that simplifies advanced mathematical calculations, covering a wide range of mathematical topics such as basic arithmetic, complex numbers, linear algebra, statistics, geometry, trigonometry, calculus, financial calculations, units and conversions, equation solvers, and math expression parsing. This library is designed to provide developers with powerful mathematical tools for various applications.", 4 | "url": "https://github.com/PB2204/Advanced-Math", 5 | "keywords": [ 6 | "JavaScript", 7 | "Advanced Math", 8 | "open-source", 9 | "hacktoberfest", 10 | "Mathematics" 11 | ], 12 | "author": "Pabitra Banerjee", 13 | "contributors": [ 14 | "Pabitra Banerjee" 15 | ], 16 | "license": "MIT", 17 | "version": "1.0.3", 18 | "main": "index.js", 19 | "devDependencies": { 20 | "jest": "^29.7.0" 21 | }, 22 | "scripts": { 23 | "test": "jest" 24 | }, 25 | "repository": { 26 | "type": "git", 27 | "url": "https://github.com/pb2204/Advanced-Math.git" 28 | }, 29 | "jest": { 30 | "modulePaths": [ 31 | "/src" 32 | ], 33 | "moduleNameMapper": { 34 | "^adv-math/(.*)$": "/src/$1" 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /adv-math/docs/Constants.md: -------------------------------------------------------------------------------- 1 | # Mathematical Constants 2 | 3 | The `Constants` module provides mathematical constants for various mathematical calculations. 4 | 5 | ## Usage 6 | 7 | To use the `Constants` module, import it and access the constants as static properties. 8 | 9 | ```javascript 10 | const Constants = require('adv-math').Constants; 11 | 12 | // Access mathematical constants 13 | const pi = Constants.PI; 14 | const e = Constants.E; 15 | const goldenRatio = Constants.GOLDEN_RATIO; 16 | const squareRoot2 = Constants.SQUARE_ROOT_2; 17 | const squareRoot3 = Constants.SQUARE_ROOT_3; 18 | ``` 19 | 20 | ## Supported Constants 21 | 22 | - `PI`: The mathematical constant π (pi). 23 | - `E`: The mathematical constant e (Euler's number). 24 | - `GOLDEN_RATIO`: The golden ratio (φ). 25 | - `SQUARE_ROOT_2`: The square root of 2 (√2). 26 | - `SQUARE_ROOT_3`: The square root of 3 (√3). 27 | - (You can add more constants as needed) 28 | 29 | ## Examples 30 | 31 | ```javascript 32 | const Constants = require('adv-math').Constants; 33 | 34 | // Access mathematical constants 35 | const pi = Constants.PI; // Result: 3.141592653589793 36 | const e = Constants.E; // Result: 2.718281828459045 37 | const goldenRatio = Constants.GOLDEN_RATIO; // Result: 1.618033988749895 38 | const squareRoot2 = Constants.SQUARE_ROOT_2; // Result: 1.4142135623730951 39 | const squareRoot3 = Constants.SQUARE_ROOT_3; // Result: 1.7320508075688772 40 | ``` 41 | -------------------------------------------------------------------------------- /adv-math/src/statistics/statistics.js: -------------------------------------------------------------------------------- 1 | class Statistics { 2 | // Method to calculate the mean (average) of an array of numbers 3 | static mean(numbers) { 4 | if (numbers.length === 0) { 5 | throw new Error('Array must not be empty.'); 6 | } 7 | 8 | const sum = numbers.reduce((acc, value) => acc + value, 0); 9 | return sum / numbers.length; 10 | } 11 | 12 | // Method to calculate the median of an array of numbers 13 | static median(numbers) { 14 | if (numbers.length === 0) { 15 | throw new Error('Array must not be empty.'); 16 | } 17 | 18 | const sortedNumbers = numbers.slice().sort((a, b) => a - b); 19 | const middle = Math.floor(sortedNumbers.length / 2); 20 | 21 | if (sortedNumbers.length % 2 === 0) { 22 | return (sortedNumbers[middle - 1] + sortedNumbers[middle]) / 2; 23 | } else { 24 | return sortedNumbers[middle]; 25 | } 26 | } 27 | 28 | // Method to calculate the standard deviation of an array of numbers 29 | static standardDeviation(numbers) { 30 | if (numbers.length < 2) { 31 | throw new Error('Array must have at least two values for standard deviation calculation.'); 32 | } 33 | 34 | const meanValue = this.mean(numbers); 35 | const squaredDifferences = numbers.map((value) => Math.pow(value - meanValue, 2)); 36 | const variance = squaredDifferences.reduce((acc, value) => acc + value, 0) / (numbers.length - 1); 37 | return Math.sqrt(variance); 38 | } 39 | } 40 | 41 | module.exports = Statistics; 42 | -------------------------------------------------------------------------------- /adv-math/docs/Random.md: -------------------------------------------------------------------------------- 1 | # Random Module 2 | 3 | The `Random` module provides methods for generating random numbers, including random integers and random floats within specified ranges. 4 | 5 | ## Usage 6 | 7 | To use the `Random` module, import it and call the methods to generate random numbers. 8 | 9 | ```javascript 10 | const Random = require('adv-math').Random; 11 | 12 | // Generate random integer 13 | const randomInt = Random.generateRandomInt(1, 10); 14 | 15 | // Generate random float 16 | const randomFloat = Random.generateRandomFloat(0, 1); 17 | ``` 18 | 19 | ## Methods 20 | 21 | ### `generateRandomInt(min, max)` 22 | 23 | Generates a random integer between `min` (inclusive) and `max` (exclusive). 24 | 25 | - `min` (Number): The minimum value (inclusive) of the random integer range. 26 | - `max` (Number): The maximum value (exclusive) of the random integer range. 27 | - Returns: A random integer within the specified range. 28 | 29 | ### `generateRandomFloat(min, max)` 30 | 31 | Generates a random floating-point number (float) between `min` (inclusive) and `max` (exclusive). 32 | 33 | - `min` (Number): The minimum value (inclusive) of the random float range. 34 | - `max` (Number): The maximum value (exclusive) of the random float range. 35 | - Returns: A random float within the specified range. 36 | 37 | ## Examples 38 | 39 | ```javascript 40 | const Random = require('adv-math').Random; 41 | 42 | // Generate random integer between 1 and 10 (inclusive of 1, exclusive of 10) 43 | const randomInt = Random.generateRandomInt(1, 10); 44 | 45 | // Generate random float between 0 and 1 (inclusive of 0, exclusive of 1) 46 | const randomFloat = Random.generateRandomFloat(0, 1); 47 | ``` 48 | -------------------------------------------------------------------------------- /adv-math/tests/basic.test.js: -------------------------------------------------------------------------------- 1 | const BasicMath = require('../src/basic/arithmetic'); 2 | const ComplexNumber = require('../src/basic/complex'); 3 | 4 | describe('BasicMath', () => { 5 | test('adds two numbers', () => { 6 | expect(BasicMath.add(2, 3)).toBe(5); 7 | }); 8 | 9 | test('subtracts two numbers', () => { 10 | expect(BasicMath.subtract(5, 2)).toBe(3); 11 | }); 12 | 13 | test('multiplies two numbers', () => { 14 | expect(BasicMath.multiply(2, 3)).toBe(6); 15 | }); 16 | 17 | test('divides two numbers', () => { 18 | expect(BasicMath.divide(6, 3)).toBe(2); 19 | }); 20 | 21 | test('throws an error when dividing by zero', () => { 22 | expect(() => { 23 | BasicMath.divide(5, 0); 24 | }).toThrow('Division by zero is not allowed.'); 25 | }); 26 | }); 27 | 28 | describe('ComplexNumber', () => { 29 | test('adds two complex numbers', () => { 30 | const complex1 = new ComplexNumber(2, 3); 31 | const complex2 = new ComplexNumber(1, 2); 32 | const result = complex1.add(complex2); 33 | expect(result.real).toBe(3); 34 | expect(result.imaginary).toBe(5); 35 | }); 36 | 37 | test('multiplies two complex numbers', () => { 38 | const complex1 = new ComplexNumber(2, 3); 39 | const complex2 = new ComplexNumber(1, 2); 40 | const result = complex1.multiply(complex2); 41 | expect(result.real).toBe(-4); 42 | expect(result.imaginary).toBe(7); 43 | }); 44 | 45 | test('calculates the magnitude of a complex number', () => { 46 | const complex = new ComplexNumber(3, 4); 47 | expect(complex.magnitude()).toBe(5); 48 | }); 49 | }); -------------------------------------------------------------------------------- /adv-math/docs/Equations.md: -------------------------------------------------------------------------------- 1 | # Equations Module 2 | 3 | The `Equations` module provides methods for solving linear and quadratic equations in JavaScript. 4 | 5 | ## Usage 6 | 7 | To use the `Equations` module, import it and use its static methods in your JavaScript code. 8 | 9 | ```javascript 10 | const Equations = require('adv-math').Equations; 11 | 12 | // Example usage 13 | const a = 2; 14 | const b = -4; 15 | const c = 2; 16 | const linearRoot = Equations.solveLinear(a, b); // Solve a linear equation 17 | const quadraticRoots = Equations.solveQuadratic(a, b, c); // Solve a quadratic equation 18 | ``` 19 | 20 | ## Methods 21 | 22 | ### `solveLinear(a, b)` 23 | 24 | Solves a linear equation of the form `ax + b = 0`. 25 | 26 | - `a` (number): The coefficient of `x`. It cannot be zero. 27 | - `b` (number): The constant term. 28 | - Returns: The root (solution) of the linear equation. 29 | 30 | ### `solveQuadratic(a, b, c)` 31 | 32 | Solves a quadratic equation of the form `ax^2 + bx + c = 0`. 33 | 34 | - `a` (number): The coefficient of `x^2`. 35 | - `b` (number): The coefficient of `x`. 36 | - `c` (number): The constant term. 37 | - Returns: An array containing the roots (solutions) of the quadratic equation. If the equation has no real roots, an error is thrown. 38 | 39 | ## Examples 40 | 41 | ```javascript 42 | const Equations = require('adv-math').Equations; 43 | 44 | // Example linear equation: 2x - 4 = 0 45 | const linearA = 2; 46 | const linearB = -4; 47 | const linearRoot = Equations.solveLinear(linearA, linearB); // Returns 2 48 | 49 | // Example quadratic equation: x^2 - 4x + 4 = 0 50 | const quadraticA = 1; 51 | const quadraticB = -4; 52 | const quadraticC = 4; 53 | const quadraticRoots = Equations.solveQuadratic(quadraticA, quadraticB, quadraticC); // Returns [2, 2] 54 | ``` 55 | -------------------------------------------------------------------------------- /adv-math/docs/Statistics.md: -------------------------------------------------------------------------------- 1 | # Statistics Module 2 | 3 | The `Statistics` module provides methods for calculating statistical measures of arrays of numbers, including mean (average), median, and standard deviation. 4 | 5 | ## Usage 6 | 7 | To use the `Statistics` module, import it and call the methods to calculate statistical measures of arrays of numbers. 8 | 9 | ```javascript 10 | const Statistics = require('adv-math').Statistics; 11 | 12 | const numbers = [1, 2, 3, 4, 5]; 13 | 14 | // Calculate mean 15 | const meanValue = Statistics.mean(numbers); 16 | 17 | // Calculate median 18 | const medianValue = Statistics.median(numbers); 19 | 20 | // Calculate standard deviation 21 | const stdDeviation = Statistics.standardDeviation(numbers); 22 | ``` 23 | 24 | ## Methods 25 | 26 | ### `mean(numbers)` 27 | 28 | Calculates the mean (average) of an array of numbers. 29 | 30 | - `numbers` (Array): An array of numeric values. 31 | - Returns: The mean (average) value of the array. 32 | 33 | ### `median(numbers)` 34 | 35 | Calculates the median of an array of numbers. 36 | 37 | - `numbers` (Array): An array of numeric values. 38 | - Returns: The median value of the array. 39 | 40 | ### `standardDeviation(numbers)` 41 | 42 | Calculates the standard deviation of an array of numbers. 43 | 44 | - `numbers` (Array): An array of numeric values. 45 | - Returns: The standard deviation of the array. 46 | 47 | ## Examples 48 | 49 | ```javascript 50 | const Statistics = require('adv-math').Statistics; 51 | 52 | const numbers = [1, 2, 3, 4, 5]; 53 | 54 | // Calculate mean (average) 55 | const meanValue = Statistics.mean(numbers); // Result: 3 56 | 57 | // Calculate median 58 | const medianValue = Statistics.median(numbers); // Result: 3 59 | 60 | // Calculate standard deviation 61 | const stdDeviation = Statistics.standardDeviation(numbers); 62 | ``` 63 | -------------------------------------------------------------------------------- /adv-math/docs/Units.md: -------------------------------------------------------------------------------- 1 | # Units Conversion Module 2 | 3 | The `Units` module provides methods for converting units of measurement, including length and temperature units. 4 | 5 | ## Usage 6 | 7 | To use the `Units` module, import it and call the methods to perform unit conversions. 8 | 9 | ```javascript 10 | const Units = require('adv-math').Units; 11 | 12 | // Convert length units 13 | const metersToFeet = Units.convertLength(1, 'meters', 'feet'); 14 | 15 | // Convert temperature units 16 | const celsiusToFahrenheit = Units.convertTemperature(25, 'Celsius', 'Fahrenheit'); 17 | ``` 18 | 19 | ## Methods 20 | 21 | ### `convertLength(value, fromUnit, toUnit)` 22 | 23 | Converts length units from one unit to another. 24 | 25 | - `value` (number): The numeric value to convert. 26 | - `fromUnit` (string): The source unit (e.g., 'meters'). 27 | - `toUnit` (string): The target unit (e.g., 'feet'). 28 | - Returns: The converted value in the target unit. 29 | 30 | ### `convertTemperature(value, fromUnit, toUnit)` 31 | 32 | Converts temperature units from one unit to another (e.g., Celsius to Fahrenheit). 33 | 34 | - `value` (number): The numeric value to convert. 35 | - `fromUnit` (string): The source temperature unit (e.g., 'Celsius'). 36 | - `toUnit` (string): The target temperature unit (e.g., 'Fahrenheit'). 37 | - Returns: The converted value in the target temperature unit. 38 | 39 | ## Supported Units 40 | 41 | ### Length Units 42 | 43 | - `meters` (m) 44 | - `feet` (ft) 45 | - (You can add more unit conversions as needed) 46 | 47 | ### Temperature Units 48 | 49 | - `Celsius` (°C) 50 | - `Fahrenheit` (°F) 51 | 52 | ## Examples 53 | 54 | ```javascript 55 | const Units = require('adv-math').Units; 56 | 57 | // Convert length units: meters to feet 58 | const metersToFeet = Units.convertLength(1, 'meters', 'feet'); // Result: 3.28084 feet 59 | 60 | // Convert temperature units: Celsius to Fahrenheit 61 | const celsiusToFahrenheit = Units.convertTemperature(25, 'Celsius', 'Fahrenheit'); // Result: 77°F 62 | ``` 63 | -------------------------------------------------------------------------------- /STRUCTURE.md: -------------------------------------------------------------------------------- 1 | ```bash 2 | adv-math/ 3 | │ 4 | ├── src/ 5 | │ ├── basic/ 6 | │ │ ├── arithmetic.js // Basic arithmetic operations 7 | │ │ ├── complex.js // Complex number operations 8 | │ │ └── ... 9 | │ │ 10 | │ ├── linear-algebra/ 11 | │ │ ├── matrix.js // Matrix operations 12 | │ │ ├── vector.js // Vector operations 13 | │ │ └── ... 14 | │ │ 15 | │ ├── statistics/ 16 | │ │ ├── statistics.js // Statistical calculations 17 | │ │ └── ... 18 | │ │ 19 | │ ├── geometry-trigonometry/ 20 | │ │ ├── geometry.js // Geometry calculations 21 | │ │ ├── trigonometry.js // Trigonometry calculations 22 | │ │ └── ... 23 | │ │ 24 | │ ├── calculus/ 25 | │ │ ├── calculus.js // Calculus operations 26 | │ │ └── ... 27 | │ │ 28 | │ ├── financial/ 29 | │ │ ├── financial.js // Financial calculations 30 | │ │ └── ... 31 | │ │ 32 | │ ├── units-conversions/ 33 | │ │ ├── units.js // Custom units and conversions 34 | │ │ └── ... 35 | │ │ 36 | │ ├── equation-solvers/ 37 | │ │ ├── equations.js // Equation solvers 38 | │ │ └── ... 39 | │ │ 40 | │ ├── expression-parsing/ 41 | │ │ ├── parser.js // Math expression parsing 42 | │ │ └── ... 43 | │ │ 44 | │ ├── random/ 45 | │ │ ├── random.js // Random number generators 46 | │ │ └── ... 47 | │ │ 48 | │ ├── constants.js // Mathematical constants 49 | │ └── index.js // Main entry point 50 | │ 51 | ├── tests/ 52 | │ ├── basic.test.js // Tests for basic operations 53 | │ ├── linear-algebra.test.js // Tests for linear algebra 54 | │ ├── ... 55 | │ └── index.test.js // Main test entry point 56 | │ 57 | ├── docs/ // Documentation 58 | │ 59 | ├── package.json // Node.js package configuration 60 | ├── README.md // Project documentation 61 | ├── .gitignore // Git ignore file 62 | └── LICENSE // Project license 63 | ``` -------------------------------------------------------------------------------- /adv-math/src/units-conversions/units.js: -------------------------------------------------------------------------------- 1 | class Units { 2 | // Method to convert length units (e.g., meters to feet) 3 | static convertLength(value, fromUnit, toUnit) { 4 | if (fromUnit === "meters" && toUnit === "feet") { 5 | return value * 3.28084; 6 | } else if (fromUnit === "feet" && toUnit === "meters") { 7 | return value * 0.3048; 8 | } else { 9 | throw new Error("Invalid length unit conversion."); 10 | } 11 | } 12 | 13 | // Method to convert temperature units (e.g., Celsius to Fahrenheit) 14 | static convertTemperature(value, fromUnit, toUnit) { 15 | if (fromUnit === "Celsius" && toUnit === "Fahrenheit") { 16 | return (value * 9) / 5 + 32; 17 | } else if (fromUnit == "Celsius" && toUnit == "Kelvin") { 18 | return value + 273.15; 19 | } else if (fromUnit === "Fahrenheit" && toUnit === "Celsius") { 20 | return ((value - 32) * 5) / 9; 21 | } else if (fromUnit == "Fahrenheit" && toUnit == "Kelvin") { 22 | return ((value + 459.67) * 5) / 9; 23 | } else if (fromUnit == "Kelvin" && toUnit == "Celsius") { 24 | return value - 273.15; 25 | } else if (fromUnit == "Kelvin" && toUnit == "Fahrenheit") { 26 | return (value * 9) / 5 - 459.67; 27 | } else { 28 | throw new Error("Invalid temperature unit conversion."); 29 | } 30 | } 31 | 32 | // Method to convert weight units (e.g., kilograms to pounds) 33 | static convertWeight(value, fromUnit, toUnit) { 34 | if (fromUnit === "kilograms" && toUnit === "pounds") { 35 | return value * 2.204623; 36 | } else if (fromUnit === "pounds" && toUnit === "kilograms") { 37 | return value * 0.4535924; 38 | } else { 39 | throw new Error("Invalid weight unit conversion."); 40 | } 41 | } 42 | static convertVolume(value, fromUnit, toUnit) { 43 | if (fromUnit === "litres" && toUnit === "fluidOZ") { 44 | return value * 33.814; 45 | } else if (fromUnit === "fluidOZ" && toUnit === "litres") { 46 | return value * 0.0295735; 47 | } else { 48 | throw new Error("Invalid volume unit conversion."); 49 | } 50 | } 51 | } 52 | 53 | module.exports = Units; 54 | -------------------------------------------------------------------------------- /adv-math/docs/Vector.md: -------------------------------------------------------------------------------- 1 | # Vector Module 2 | 3 | The `Vector` module provides methods for performing vector operations, including addition, subtraction, dot product, and cross product. 4 | 5 | ## Usage 6 | 7 | To use the `Vector` module, import it and create vector instances to perform operations. 8 | 9 | ```javascript 10 | const Vector = require('adv-math').Vector; 11 | 12 | // Create vectors 13 | const vectorA = new Vector([1, 2, 3]); 14 | const vectorB = new Vector([4, 5, 6]); 15 | 16 | // Perform vector operations 17 | const resultAddition = vectorA.add(vectorB); 18 | const resultSubtraction = vectorA.subtract(vectorB); 19 | const resultDotProduct = vectorA.dot(vectorB); 20 | const resultCrossProduct = vectorA.cross(vectorB); 21 | ``` 22 | 23 | ## Methods 24 | 25 | ### `add(vector)` 26 | 27 | Performs vector addition between two vectors. 28 | 29 | - `vector` (Vector): The vector to be added to the current vector. 30 | - Returns: A new vector representing the result of the addition. 31 | 32 | ### `subtract(vector)` 33 | 34 | Performs vector subtraction between two vectors. 35 | 36 | - `vector` (Vector): The vector to be subtracted from the current vector. 37 | - Returns: A new vector representing the result of the subtraction. 38 | 39 | ### `dot(vector)` 40 | 41 | Calculates the dot product (inner product) of two vectors. 42 | 43 | - `vector` (Vector): The vector with which the dot product will be calculated. 44 | - Returns: A scalar (number) representing the dot product of the two vectors. 45 | 46 | ### `cross(vector)` 47 | 48 | Calculates the cross product of two 3D vectors. 49 | 50 | - `vector` (Vector): The 3D vector with which the cross product will be calculated. 51 | - Returns: A new 3D vector representing the cross product of the two vectors. 52 | 53 | ## Examples 54 | 55 | ```javascript 56 | const Vector = require('adv-math').Vector; 57 | 58 | // Create vectors 59 | const vectorA = new Vector([1, 2, 3]); 60 | const vectorB = new Vector([4, 5, 6]); 61 | 62 | // Perform vector operations 63 | const resultAddition = vectorA.add(vectorB); 64 | const resultSubtraction = vectorA.subtract(vectorB); 65 | const resultDotProduct = vectorA.dot(vectorB); 66 | const resultCrossProduct = vectorA.cross(vectorB); 67 | ``` 68 | -------------------------------------------------------------------------------- /adv-math/docs/BasicMath.md: -------------------------------------------------------------------------------- 1 | # BasicMath Module 2 | 3 | The `BasicMath` module provides basic arithmetic operations for addition, subtraction, multiplication, and division. 4 | 5 | ## Usage 6 | 7 | Import the `BasicMath` module and use its static methods in your JavaScript code. 8 | 9 | ```javascript 10 | const BasicMath = require('adv-math').BasicMath; 11 | 12 | // Example usage 13 | const result = BasicMath.add(2, 3); // Returns 5 14 | const difference = BasicMath.subtract(5, 3); // Returns 2 15 | const product = BasicMath.multiply(2, 3); // Returns 6 16 | const quotient = BasicMath.divide(6, 2); // Returns 3 17 | ``` 18 | 19 | ## Methods 20 | 21 | ### `add(a, b)` 22 | 23 | Adds two numbers and returns the result. 24 | 25 | - `a` (number): The first number. 26 | - `b` (number): The second number. 27 | - Returns: The sum of `a` and `b`. 28 | 29 | ### `subtract(a, b)` 30 | 31 | Subtracts the second number from the first number and returns the result. 32 | 33 | - `a` (number): The first number. 34 | - `b` (number): The number to subtract. 35 | - Returns: The result of `a - b`. 36 | 37 | ### `multiply(a, b)` 38 | 39 | Multiplies two numbers and returns the result. 40 | 41 | - `a` (number): The first number. 42 | - `b` (number): The second number. 43 | - Returns: The product of `a` and `b`. 44 | 45 | ### `divide(a, b)` 46 | 47 | Divides the first number by the second number and returns the result. Throws an error if division by zero is attempted. 48 | 49 | - `a` (number): The numerator. 50 | - `b` (number): The denominator. 51 | - Returns: The result of `a / b`. 52 | - Throws: An error if `b` is 0 (division by zero). 53 | 54 | ## Examples 55 | 56 | ```javascript 57 | const BasicMath = require('adv-math').BasicMath; 58 | 59 | // Addition 60 | const sum = BasicMath.add(4, 5); // Returns 9 61 | 62 | // Subtraction 63 | const difference = BasicMath.subtract(10, 3); // Returns 7 64 | 65 | // Multiplication 66 | const product = BasicMath.multiply(6, 8); // Returns 48 67 | 68 | // Division 69 | const quotient = BasicMath.divide(20, 5); // Returns 4 70 | 71 | // Division by zero (throws an error) 72 | try { 73 | BasicMath.divide(10, 0); // Throws an error 74 | } catch (error) { 75 | console.error(error.message); // Outputs "Division by zero is not allowed." 76 | } 77 | ``` -------------------------------------------------------------------------------- /adv-math/tests/units-conversions.test.js: -------------------------------------------------------------------------------- 1 | const Units = require("../src/units-conversions/units"); 2 | 3 | describe("Units", () => { 4 | test("converts meters to feet", () => { 5 | expect(Units.convertLength(5, "meters", "feet")).toBeCloseTo(16.4042, 3); 6 | }); 7 | 8 | test("converts feet to meters", () => { 9 | expect(Units.convertLength(10, "feet", "meters")).toBeCloseTo(3.048, 2); 10 | }); 11 | 12 | test("converts Celsius to Fahrenheit", () => { 13 | expect(Units.convertTemperature(25, "Celsius", "Fahrenheit")).toBeCloseTo( 14 | 77, 15 | 1 16 | ); 17 | }); 18 | test("converts Celsius to Kelvin", () => { 19 | expect(Units.convertTemperature(25, "Celsius", "Kelvin")).toBeCloseTo( 20 | 298.15, 21 | 1 22 | ); 23 | }); 24 | test("converts Fahrenheit to Kelvin", () => { 25 | expect(Units.convertTemperature(68, "Fahrenheit", "Kelvin")).toBeCloseTo( 26 | 293.15, 27 | 1 28 | ); 29 | }); 30 | test("converts Fahrenheit to Celsius", () => { 31 | expect(Units.convertTemperature(68, "Fahrenheit", "Celsius")).toBeCloseTo( 32 | 20, 33 | 1 34 | ); 35 | }); 36 | test("converts Kelvin to Celsius", () => { 37 | expect(Units.convertTemperature(300, "Kelvin", "Celsius")).toBeCloseTo( 38 | 26.85, 39 | 1 40 | ); 41 | }); 42 | test("converts Kelvin to Fahrenheit", () => { 43 | expect(Units.convertTemperature(300, "Kelvin", "Fahrenheit")).toBeCloseTo( 44 | 80.33, 45 | 1 46 | ); 47 | }); 48 | 49 | test("converts kilograms to pounds", () => { 50 | expect(Units.convertWeight(5, "kilograms", "pounds")).toBeCloseTo( 51 | 11.0231, 52 | 3 53 | ); 54 | }); 55 | test("converts pounds to kilograms", () => { 56 | expect(Units.convertWeight(10, "pounds", "kilograms")).toBeCloseTo( 57 | 4.5359, 58 | 3 59 | ); 60 | }); 61 | test("converts litres to fluid ounces", () => { 62 | expect(Units.convertVolume(1, "litres", "fluidOZ")).toBeCloseTo( 63 | 33.814, 64 | 2 65 | ); 66 | }); 67 | test("converts fluid ounces to litres", () => { 68 | expect(Units.convertVolume(100, "fluidOZ", "litres")).toBeCloseTo( 69 | 2.95735, 70 | 3 71 | ); 72 | }); 73 | // Add more test cases as needed 74 | }); 75 | -------------------------------------------------------------------------------- /adv-math/src/linear-algebra/vector.js: -------------------------------------------------------------------------------- 1 | class Vector { 2 | constructor(components) { 3 | this.components = [...components]; 4 | this.dimension = components.length; 5 | } 6 | 7 | // Method to perform vector addition 8 | add(vector) { 9 | if (this.dimension !== vector.dimension) { 10 | throw new Error('Vector dimensions must match for addition.'); 11 | } 12 | 13 | const resultComponents = []; 14 | for (let i = 0; i < this.dimension; i++) { 15 | resultComponents[i] = this.components[i] + vector.components[i]; 16 | } 17 | 18 | return new Vector(resultComponents); 19 | } 20 | 21 | // Method to perform vector subtraction 22 | subtract(vector) { 23 | if (this.dimension !== vector.dimension) { 24 | throw new Error('Vector dimensions must match for subtraction.'); 25 | } 26 | 27 | const resultComponents = []; 28 | for (let i = 0; i < this.dimension; i++) { 29 | resultComponents[i] = this.components[i] - vector.components[i]; 30 | } 31 | 32 | return new Vector(resultComponents); 33 | } 34 | 35 | // Method to calculate the dot product of two vectors 36 | dot(vector) { 37 | if (this.dimension !== vector.dimension) { 38 | throw new Error('Vector dimensions must match for dot product.'); 39 | } 40 | 41 | let product = 0; 42 | for (let i = 0; i < this.dimension; i++) { 43 | product += this.components[i] * vector.components[i]; 44 | } 45 | 46 | return product; 47 | } 48 | 49 | // Method to calculate the cross product of two 3D vectors 50 | cross(vector) { 51 | if (this.dimension !== 3 || vector.dimension !== 3) { 52 | throw new Error('Cross product is defined for 3D vectors only.'); 53 | } 54 | 55 | const x = this.components[1] * vector.components[2] - this.components[2] * vector.components[1]; 56 | const y = this.components[2] * vector.components[0] - this.components[0] * vector.components[2]; 57 | const z = this.components[0] * vector.components[1] - this.components[1] * vector.components[0]; 58 | 59 | return new Vector([x, y, z]); 60 | } 61 | } 62 | 63 | module.exports = Vector; 64 | -------------------------------------------------------------------------------- /adv-math/docs/Geometry.md: -------------------------------------------------------------------------------- 1 | # Geometry Module 2 | 3 | The `Geometry` module provides methods for performing geometric calculations, including area and perimeter calculations for rectangles and circles. 4 | 5 | ## Usage 6 | 7 | To use the `Geometry` module, import it and use its methods in your JavaScript code. 8 | 9 | ```javascript 10 | const Geometry = require('adv-math').Geometry; 11 | 12 | // Example usage 13 | const length = 10; 14 | const width = 5; 15 | const radius = 3; 16 | 17 | // Calculate the area and perimeter of a rectangle 18 | const rectangleArea = Geometry.rectangleArea(length, width); 19 | const rectanglePerimeter = Geometry.rectanglePerimeter(length, width); 20 | 21 | // Calculate the area and circumference of a circle 22 | const circleArea = Geometry.circleArea(radius); 23 | const circleCircumference = Geometry.circleCircumference(radius); 24 | ``` 25 | 26 | ## Methods 27 | 28 | ### `rectangleArea(length, width)` 29 | 30 | Calculates the area of a rectangle. 31 | 32 | - `length` (number): The length of the rectangle. 33 | - `width` (number): The width of the rectangle. 34 | - Returns: The area of the rectangle. 35 | 36 | ### `rectanglePerimeter(length, width)` 37 | 38 | Calculates the perimeter of a rectangle. 39 | 40 | - `length` (number): The length of the rectangle. 41 | - `width` (number): The width of the rectangle. 42 | - Returns: The perimeter of the rectangle. 43 | 44 | ### `circleArea(radius)` 45 | 46 | Calculates the area of a circle. 47 | 48 | - `radius` (number): The radius of the circle. 49 | - Returns: The area of the circle. 50 | 51 | ### `circleCircumference(radius)` 52 | 53 | Calculates the circumference of a circle. 54 | 55 | - `radius` (number): The radius of the circle. 56 | - Returns: The circumference of the circle. 57 | 58 | ## Examples 59 | 60 | ```javascript 61 | const Geometry = require('adv-math').Geometry; 62 | 63 | // Example calculations 64 | const length = 10; 65 | const width = 5; 66 | const radius = 3; 67 | 68 | const rectangleArea = Geometry.rectangleArea(length, width); // Returns 50 69 | const rectanglePerimeter = Geometry.rectanglePerimeter(length, width); // Returns 30 70 | const circleArea = Geometry.circleArea(radius); // Returns 28.274333882308138 71 | const circleCircumference = Geometry.circleCircumference(radius); // Returns 18.84955592153876 72 | ``` 73 | -------------------------------------------------------------------------------- /adv-math/docs/Matrix.md: -------------------------------------------------------------------------------- 1 | # Matrix Module 2 | 3 | The `Matrix` module provides methods for performing matrix operations, including addition, subtraction, and multiplication of matrices. 4 | 5 | ## Usage 6 | 7 | To use the `Matrix` module, import it and create matrix instances to perform operations. 8 | 9 | ```javascript 10 | const Matrix = require('adv-math').Matrix; 11 | 12 | // Create matrices 13 | const matrixA = new Matrix(2, 3); 14 | matrixA.data = [[1, 2, 3], [4, 5, 6]]; 15 | 16 | const matrixB = new Matrix(2, 3); 17 | matrixB.data = [[7, 8, 9], [10, 11, 12]]; 18 | 19 | // Perform matrix operations 20 | const resultAddition = Matrix.add(matrixA, matrixB); 21 | const resultSubtraction = Matrix.subtract(matrixA, matrixB); 22 | const resultMultiplication = Matrix.multiply(matrixA, matrixB); 23 | ``` 24 | 25 | ## Methods 26 | 27 | ### `add(matrixA, matrixB)` 28 | 29 | Performs matrix addition between two matrices, `matrixA` and `matrixB`. 30 | 31 | - `matrixA` (Matrix): The first matrix for addition. 32 | - `matrixB` (Matrix): The second matrix for addition. 33 | - Returns: A new matrix representing the result of the addition. 34 | 35 | ### `subtract(matrixA, matrixB)` 36 | 37 | Performs matrix subtraction between two matrices, `matrixA` and `matrixB`. 38 | 39 | - `matrixA` (Matrix): The matrix from which `matrixB` will be subtracted. 40 | - `matrixB` (Matrix): The matrix to be subtracted from `matrixA`. 41 | - Returns: A new matrix representing the result of the subtraction. 42 | 43 | ### `multiply(matrixA, matrixB)` 44 | 45 | Performs matrix multiplication between two matrices, `matrixA` and `matrixB`. 46 | 47 | - `matrixA` (Matrix): The first matrix for multiplication. 48 | - `matrixB` (Matrix): The second matrix for multiplication. 49 | - Returns: A new matrix representing the result of the multiplication. 50 | 51 | ## Examples 52 | 53 | ```javascript 54 | const Matrix = require('adv-math').Matrix; 55 | 56 | // Create matrices 57 | const matrixA = new Matrix(2, 3); 58 | matrixA.data = [[1, 2, 3], [4, 5, 6]]; 59 | 60 | const matrixB = new Matrix(3, 2); 61 | matrixB.data = [[7, 8], [9, 10], [11, 12]]; 62 | 63 | // Perform matrix operations 64 | const resultAddition = Matrix.add(matrixA, matrixB); 65 | const resultSubtraction = Matrix.subtract(matrixA, matrixB); 66 | const resultMultiplication = Matrix.multiply(matrixA, matrixB); 67 | ``` 68 | -------------------------------------------------------------------------------- /adv-math/docs/Financial.md: -------------------------------------------------------------------------------- 1 | # Financial Module 2 | 3 | The `Financial` module provides methods for financial calculations, including calculating future values, compound interest, and present values. 4 | 5 | ## Usage 6 | 7 | To use the `Financial` module, import it and use its methods in your JavaScript code. 8 | 9 | ```javascript 10 | const Financial = require('adv-math').Financial; 11 | 12 | // Example usage 13 | const principal = 1000; // Initial investment 14 | const rate = 0.05; // Annual interest rate (5%) 15 | const time = 5; // Number of years 16 | 17 | // Calculate future value with compound interest 18 | const futureValue = Financial.futureValue(principal, rate, time); 19 | 20 | // Calculate compound interest earned 21 | const compoundInterest = Financial.compoundInterest(principal, rate, time); 22 | 23 | // Calculate present value 24 | const presentValue = Financial.presentValue(futureValue, rate, time); 25 | ``` 26 | 27 | ## Methods 28 | 29 | ### `futureValue(principal, rate, time)` 30 | 31 | Calculates the future value of an investment with compound interest. 32 | 33 | - `principal` (number): The initial investment or principal amount. 34 | - `rate` (number): The annual interest rate (decimal). 35 | - `time` (number): The number of years. 36 | - Returns: The future value of the investment. 37 | 38 | ### `compoundInterest(principal, rate, time)` 39 | 40 | Calculates the compound interest earned on an investment. 41 | 42 | - `principal` (number): The initial investment or principal amount. 43 | - `rate` (number): The annual interest rate (decimal). 44 | - `time` (number): The number of years. 45 | - Returns: The compound interest earned. 46 | 47 | ### `presentValue(futureValue, rate, time)` 48 | 49 | Calculates the present value of a future amount with discounting. 50 | 51 | - `futureValue` (number): The future amount to be discounted. 52 | - `rate` (number): The annual interest rate (decimal). 53 | - `time` (number): The number of years. 54 | - Returns: The present value of the future amount. 55 | 56 | ## Examples 57 | 58 | ```javascript 59 | const Financial = require('adv-math').Financial; 60 | 61 | // Example calculations 62 | const principal = 1000; 63 | const rate = 0.05; 64 | const time = 5; 65 | 66 | const futureValue = Financial.futureValue(principal, rate, time); // Returns 1276.2830362313579 67 | const compoundInterest = Financial.compoundInterest(principal, rate, time); // Returns 276.2830362313579 68 | const presentValue = Financial.presentValue(futureValue, rate, time); // Returns 1000 69 | ``` 70 | -------------------------------------------------------------------------------- /adv-math/docs/Calculus.md: -------------------------------------------------------------------------------- 1 | # Calculus Module 2 | 3 | The `Calculus` module provides methods for performing basic calculus operations, including calculating the derivative of a function at a given point using numerical differentiation (finite difference method) and calculating the definite integral of a function between two points using numerical integration (trapezoidal rule). 4 | 5 | ## Usage 6 | 7 | To use the `Calculus` module, import it and use its static methods in your JavaScript code. 8 | 9 | ```javascript 10 | const Calculus = require('adv-math').Calculus; 11 | 12 | // Example usage 13 | const func = (x) => x * x; // Example function 14 | const point = 2; // Point at which to calculate the derivative 15 | const derivative = Calculus.derivative(func, point); // Calculate the derivative 16 | const a = 0; // Lower bound of the integral 17 | const b = 1; // Upper bound of the integral 18 | const n = 1000; // Number of subintervals for numerical integration 19 | const integral = Calculus.integral(func, a, b, n); // Calculate the definite integral 20 | ``` 21 | 22 | ## Methods 23 | 24 | ### `derivative(func, point, h = 0.001)` 25 | 26 | Calculates the derivative of a function at a given point using numerical differentiation (finite difference method). 27 | 28 | - `func` (function): The function for which to calculate the derivative. 29 | - `point` (number): The point at which to calculate the derivative. 30 | - `h` (number, optional): The step size for numerical differentiation (default is 0.001). 31 | - Returns: The numerical derivative of the function at the specified point. 32 | 33 | ### `integral(func, a, b, n = 1000)` 34 | 35 | Calculates the definite integral of a function between two points using numerical integration (trapezoidal rule). 36 | 37 | - `func` (function): The function for which to calculate the integral. 38 | - `a` (number): The lower bound of the integral. 39 | - `b` (number): The upper bound of the integral. 40 | - `n` (number, optional): The number of subintervals for numerical integration (default is 1000). 41 | - Returns: The numerical value of the definite integral of the function between `a` and `b`. 42 | 43 | ## Examples 44 | 45 | ```javascript 46 | const Calculus = require('adv-math').Calculus; 47 | 48 | // Example function 49 | const func = (x) => x * x; 50 | 51 | // Calculate the derivative at a point 52 | const point = 2; 53 | const derivative = Calculus.derivative(func, point); // Returns approximately 4.001 54 | 55 | // Calculate the definite integral between two points 56 | const a = 0; 57 | const b = 1; 58 | const n = 1000; 59 | const integral = Calculus.integral(func, a, b, n); // Returns approximately 0.3335 60 | ``` -------------------------------------------------------------------------------- /adv-math/src/equation-solvers/equations.js: -------------------------------------------------------------------------------- 1 | class Equations { 2 | // Method to solve a linear equation of the form: ax + b = 0 3 | static solveLinear(a, b) { 4 | if (a === 0) { 5 | throw new Error('The coefficient of x cannot be zero.'); 6 | } 7 | return -b / a; 8 | } 9 | 10 | // Method to solve a quadratic equation of the form: ax^2 + bx + c = 0 11 | static solveQuadratic(a, b, c) { 12 | const discriminant = b * b - 4 * a * c; 13 | if (discriminant < 0) { 14 | throw new Error('The equation has no real roots.'); 15 | } 16 | const sqrtDiscriminant = Math.sqrt(discriminant); 17 | const x1 = (-b + sqrtDiscriminant) / (2 * a); 18 | const x2 = (-b - sqrtDiscriminant) / (2 * a); 19 | return [x1, x2]; 20 | } 21 | 22 | // Method to solve a cubic equation of the form: ax^3 + bx^2 + cx + d = 0 23 | static solveCubic(a, b, c, d) { 24 | // Implementation of Cardano's method to solve cubic equations 25 | if (a === 0) { 26 | throw new Error('The coefficient of x^3 cannot be zero.'); 27 | } 28 | 29 | const delta0 = b * b - 3 * a * c; 30 | const delta1 = 2 * b * b * b - 9 * a * b * c + 27 * a * a * d; 31 | const C = Math.cbrt((delta1 + Math.sqrt(delta1 * delta1 - 4 * delta0 * delta0 * delta0)) / 2); 32 | const x1 = -(1 / (3 * a)) * (b + C + delta0 / C); 33 | return [x1]; 34 | } 35 | 36 | // Method to solve an exponential equation of the form: a^x = b 37 | static solveExponential(a, b) { 38 | if (a <= 0 || a === 1 || b <= 0) { 39 | throw new Error('Values of a and b must be positive, and a cannot be equal to 1.'); 40 | } 41 | return Math.log(b) / Math.log(a); 42 | } 43 | 44 | // Method to solve a logarithmic equation of the form: log_a(bx + c) = d 45 | static solveLogarithmic(a, b, c, d) { 46 | if (a <= 0 || a === 1 || b <= 0 || c < 0) { 47 | throw new Error('Values of a, b, and c must be positive, and a cannot be equal to 1.'); 48 | } 49 | const logValue = d / Math.log(a); 50 | return (Math.pow(a, logValue) - c) / b; 51 | } 52 | 53 | // Method to solve a system of linear equations 54 | static solveLinearSystem(a1, b1, c1, a2, b2, c2) { 55 | const determinant = a1 * b2 - a2 * b1; 56 | if (determinant === 0) { 57 | throw new Error('The system of equations has no unique solution.'); 58 | } 59 | const x = (c1 * b2 - c2 * b1) / determinant; 60 | const y = (a1 * c2 - a2 * c1) / determinant; 61 | return [x, y]; 62 | } 63 | } 64 | 65 | module.exports = Equations; 66 | -------------------------------------------------------------------------------- /adv-math/docs/ExpressionEvaluator.md: -------------------------------------------------------------------------------- 1 | # ExpressionEvaluator Class 2 | 3 | The `ExpressionEvaluator` class is a part of the `adv-math` package and is designed to evaluate mathematical expressions in string format. It can handle basic arithmetic operations, parentheses, and operator precedence. 4 | 5 | ## Usage 6 | 7 | To use the `ExpressionEvaluator` class, follow these steps: 8 | 9 | 1. Import the `ExpressionEvaluator` class into your JavaScript file. 10 | 11 | ```javascript 12 | const ExpressionEvaluator = require('adv-math').ExpressionEvaluator; 13 | ``` 14 | 15 | 2. Call the `evaluateExpression` method of the `ExpressionEvaluator` class with a mathematical expression as a string. 16 | 17 | ```javascript 18 | const expression = '3 + 5 * (2 - 4)'; 19 | const result = ExpressionEvaluator.evaluateExpression(expression); 20 | console.log('Result:', result); 21 | ``` 22 | 23 | This will evaluate the expression and return the result. 24 | 25 | ## Methods 26 | 27 | ### `evaluateExpression(expression: string): number` 28 | 29 | Evaluates the mathematical expression provided as a string and returns the result as a number. 30 | 31 | - `expression` (string): The mathematical expression to be evaluated. 32 | 33 | ## Examples 34 | 35 | ### Example 1: Basic Arithmetic 36 | 37 | ```javascript 38 | const expression = '2 + 3 * 4 - 1'; 39 | const result = ExpressionEvaluator.evaluateExpression(expression); 40 | console.log('Result:', result); // Output: 13 41 | ``` 42 | 43 | ### Example 2: Using Parentheses 44 | 45 | ```javascript 46 | const expression = '(2 + 3) * (4 - 1)'; 47 | const result = ExpressionEvaluator.evaluateExpression(expression); 48 | console.log('Result:', result); // Output: 15 49 | ``` 50 | 51 | ### Example 3: Handling Operator Precedence 52 | 53 | ```javascript 54 | const expression = '3 + 5 * (2 - 4)'; 55 | const result = ExpressionEvaluator.evaluateExpression(expression); 56 | console.log('Result:', result); // Output: -7 57 | ``` 58 | 59 | ### Example 4: Error Handling (Division by Zero) 60 | 61 | ```javascript 62 | const expression = '5 / 0'; 63 | try { 64 | const result = ExpressionEvaluator.evaluateExpression(expression); 65 | console.log('Result:', result); 66 | } catch (error) { 67 | console.error('Error:', error.message); // Output: Error: Division by zero 68 | } 69 | ``` 70 | 71 | ## Notes 72 | 73 | - The `ExpressionEvaluator` class supports addition (`+`), subtraction (`-`), multiplication (`*`), and division (`/`) operations. 74 | - It follows operator precedence, with `*` and `/` having higher precedence than `+` and `-`. 75 | - Use parentheses to override operator precedence as needed. 76 | 77 | ## License 78 | 79 | This class is part of the `adv-math` package and is subject to the package's [license](../LICENSE). -------------------------------------------------------------------------------- /adv-math/tests/expression-evaluator.test.js: -------------------------------------------------------------------------------- 1 | const ExpressionEvaluator = require('../src/expression-evaluator/expression-evaluator'); 2 | 3 | describe('ExpressionEvaluator', () => { 4 | it('should evaluate a simple expression', () => { 5 | const expression = '4 + 6'; 6 | const result = ExpressionEvaluator.evaluateExpression(expression); 7 | expect(result).toBe(10); 8 | }); 9 | 10 | it('should handle subtraction', () => { 11 | const expression = '10 - 3'; 12 | const result = ExpressionEvaluator.evaluateExpression(expression); 13 | expect(result).toBe(7); 14 | }); 15 | 16 | it('should handle multiplication', () => { 17 | const expression = '5 * 8'; 18 | const result = ExpressionEvaluator.evaluateExpression(expression); 19 | expect(result).toBe(40); 20 | }); 21 | 22 | it('should handle division', () => { 23 | const expression = '12 / 4'; 24 | const result = ExpressionEvaluator.evaluateExpression(expression); 25 | expect(result).toBe(3); 26 | }); 27 | 28 | // it('should handle parentheses', () => { 29 | // const expression = '4 * (6 + 2)'; // Valid expression with parentheses 30 | // expect(ExpressionEvaluator.evaluateExpression(expression)).toEqual(32); 31 | // }); 32 | 33 | // it('should handle complex expressions', () => { 34 | // const expression = '4 * (6 + 2) / 2'; // Valid complex expression 35 | // expect(ExpressionEvaluator.evaluateExpression(expression)).toEqual(16); 36 | // }); 37 | 38 | // it('should throw an error for invalid expressions', () => { 39 | // const expression = '4 + * 6'; // Invalid expression 40 | // expect(() => ExpressionEvaluator.evaluateExpression(expression)).toThrowError('Invalid operator'); 41 | // }); 42 | 43 | it('should handle floating-point numbers', () => { 44 | const expression = '1.5 + 2.3'; 45 | const result = ExpressionEvaluator.evaluateExpression(expression); 46 | expect(result).toBe(3.8); 47 | }); 48 | 49 | it('should throw an error for division by zero', () => { 50 | const expression = '5 / 0'; // Division by zero 51 | expect(() => ExpressionEvaluator.evaluateExpression(expression)).toThrowError('Division by zero'); 52 | }); 53 | 54 | it('should throw an error for mismatched parentheses', () => { 55 | const expression = '4 * (6 + 2'; // Mismatched parentheses 56 | expect(() => ExpressionEvaluator.evaluateExpression(expression)).toThrowError('Invalid operator'); 57 | }); 58 | 59 | it('should throw an error for invalid characters', () => { 60 | const expression = '4 # 6'; // Invalid character # 61 | expect(() => ExpressionEvaluator.evaluateExpression(expression)).toThrowError('Invalid character: #'); 62 | }); 63 | }); 64 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Code of Conduct 2 | 3 | ## Purpose 4 | 5 | The `adv-math` community is committed to providing a welcoming and inclusive environment for all contributors, regardless of their background, experience level, or identity. We want to ensure that all interactions within our community are respectful and constructive. 6 | 7 | This Code of Conduct outlines our expectations for behavior, both within the project's codebase and in all community spaces, such as GitHub issues, pull requests, and discussions. 8 | 9 | ## Expected Behavior 10 | 11 | As a contributor or participant in the `adv-math` community, you are expected to: 12 | 13 | - Be respectful and considerate of others' viewpoints and ideas. 14 | - Use inclusive language and avoid offensive or derogatory comments. 15 | - Provide constructive and helpful feedback to fellow contributors. 16 | - Value and appreciate diverse perspectives and experiences. 17 | - Respect and adhere to the project's guidelines and conventions. 18 | - Help create a positive and inclusive community for everyone. 19 | 20 | ## Unacceptable Behavior 21 | 22 | Unacceptable behavior includes but is not limited to: 23 | 24 | - Harassment, discrimination, or bullying of any kind. 25 | - Offensive comments, slurs, or insults. 26 | - Trolling, spamming, or any form of disruptive behavior. 27 | - Engaging in personal attacks or online harassment. 28 | - Violating the privacy of others. 29 | - Promoting or encouraging any form of discrimination. 30 | - Any behavior that violates the project's guidelines and code of conduct. 31 | 32 | ## Reporting and Enforcement 33 | 34 | If you encounter or witness behavior that violates this Code of Conduct, we encourage you to report it promptly. To report an issue, please: 35 | 36 | 1. Contact the project maintainers directly via email or through other private channels if you feel comfortable doing so. 37 | 2. If the issue is related to a public discussion or interaction, report it by creating a GitHub issue. 38 | 39 | All reports will be taken seriously and treated with confidentiality. We are committed to addressing and resolving any issues promptly. 40 | 41 | ## Enforcement 42 | 43 | The project maintainers have the right and responsibility to remove, edit, or reject any contributions, comments, or other interactions that violate this Code of Conduct. We may also temporarily or permanently ban any contributor who engages in unacceptable behavior. 44 | 45 | ## Attribution 46 | 47 | This Code of Conduct is adapted from the Contributor Covenant, version 2.1, available at [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html](https://www.contributor-covenant.org/version/2/1/code_of_conduct.html). 48 | 49 | ## Contact Information 50 | 51 | If you have questions or need to report an issue related to this Code of Conduct, please contact the project maintainers: 52 | 53 | - [Pabitra Banerjee](mailto:rockstarpabitra2204@gmail.com) 54 | 55 | We are here to help ensure that the `adv-math` community remains welcoming and respectful for all. 56 | -------------------------------------------------------------------------------- /adv-math/docs/Index.md: -------------------------------------------------------------------------------- 1 | # Advanced Mathematics Library 2 | 3 | The Advanced Mathematics Library (`adv-math`) is a comprehensive JavaScript library that provides a wide range of mathematical functions and operations. This library is designed to assist developers in performing advanced mathematical calculations in various domains such as basic arithmetic, linear algebra, statistics, geometry, trigonometry, calculus, financial mathematics, and more. 4 | 5 | ## Installation 6 | 7 | You can install the `adv-math` library using npm: 8 | 9 | ```bash 10 | npm install adv-math 11 | ``` 12 | 13 | ## Usage 14 | 15 | To use the `adv-math` library, you can import the specific modules or functions you need for your mathematical calculations. Below is a list of available modules: 16 | 17 | - [BasicMath](#basicmath) 18 | - [ComplexNumber](#complexnumber) 19 | - [Matrix](#matrix) 20 | - [Vector](#vector) 21 | - [Statistics](#statistics) 22 | - [Geometry](#geometry) 23 | - [Trigonometry](#trigonometry) 24 | - [Calculus](#calculus) 25 | - [Financial](#financial) 26 | - [Units](#units) 27 | - [Equations](#equations) 28 | - [Parser](#parser) 29 | - [Random](#random) 30 | 31 | ### BasicMath 32 | 33 | The `BasicMath` module provides basic arithmetic operations such as addition, subtraction, multiplication, and division. 34 | 35 | Usage example: 36 | 37 | ```javascript 38 | const BasicMath = require('adv-math').BasicMath; 39 | 40 | const result = BasicMath.add(5, 3); // Result: 8 41 | ``` 42 | 43 | ### ComplexNumber 44 | 45 | The `ComplexNumber` module supports complex number operations, including addition, subtraction, multiplication, and magnitude calculation. 46 | 47 | Usage example: 48 | 49 | ```javascript 50 | const ComplexNumber = require('adv-math').ComplexNumber; 51 | 52 | const num1 = new ComplexNumber(3, 4); 53 | const num2 = new ComplexNumber(1, 2); 54 | const sum = num1.add(num2); // Result: ComplexNumber { real: 4, imaginary: 6 } 55 | ``` 56 | 57 | (Continue with descriptions and examples for other modules...) 58 | 59 | ## Documentation 60 | 61 | For detailed documentation and usage examples of each module, you can refer to the corresponding Markdown files in the [docs](docs/) directory of this repository. 62 | 63 | - [BasicMath.md](docs/BasicMath.md) 64 | - [ComplexNumber.md](docs/ComplexNumber.md) 65 | - [Matrix.md](docs/Matrix.md) 66 | - [Vector.md](docs/Vector.md) 67 | - [Statistics.md](docs/Statistics.md) 68 | - [Geometry.md](docs/Geometry.md) 69 | - [Trigonometry.md](docs/Trigonometry.md) 70 | - [Calculus.md](docs/Calculus.md) 71 | - [Financial.md](docs/Financial.md) 72 | - [Units.md](docs/Units.md) 73 | - [Equations.md](docs/Equations.md) 74 | - [Parser.md](docs/Parser.md) 75 | - [Random.md](docs/Random.md) 76 | 77 | These documentation files provide comprehensive information on each module's functionality and usage. 78 | 79 | ## Contributing 80 | 81 | If you would like to contribute to the `adv-math` library, please check the [CONTRIBUTING.md](CONTRIBUTING.md) file for guidelines and information on how to get started with development. 82 | 83 | ## License 84 | 85 | This project is licensed under the [MIT License](LICENSE). 86 | ``` 87 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to adv-math 2 | 3 | 👍 Thank you for your interest in contributing to `adv-math`! We welcome contributions from the community to help improve and enhance this mathematical library. 4 | 5 | ## How to Contribute 6 | 7 | Contributing to `adv-math` is easy and we appreciate every contribution. Follow these steps to get started: 8 | 9 | 1. **Fork the Repository** 10 | 11 | Click the "Fork" button in the top right corner of this repository to create your own copy. 12 | 13 | 2. **Clone the Repository** 14 | 15 | Clone the repository to your local machine using the following command (replace `[YOUR_USERNAME]` with your GitHub username): 16 | 17 | ```bash 18 | git clone https://github.com/[YOUR_USERNAME]/adv-math.git 19 | ``` 20 | 21 | 3. **Create a Branch** 22 | 23 | Create a new branch for your contribution. Name the branch something related to the feature or bug you are working on. 24 | 25 | ```bash 26 | git checkout -b feature-or-bug-fix-name 27 | ``` 28 | 29 | 4. **Make Changes** 30 | 31 | Make your desired changes to the codebase. Ensure that your changes follow the coding standards and guidelines of the project. 32 | 33 | 5. **Write Tests** 34 | 35 | If you are adding new functionality or fixing a bug, write tests for your code in the `tests/` directory. Ensure that your tests cover the functionality you have added or fixed. 36 | 37 | 6. **Run Tests** 38 | 39 | Before submitting your changes, make sure all tests pass. You can run tests using the following command: 40 | 41 | ```bash 42 | npm test 43 | ``` 44 | 45 | or 46 | 47 | ```bash 48 | yarn test 49 | ``` 50 | 51 | Fix any failing tests before proceeding. 52 | 53 | 7. **Commit Changes** 54 | 55 | Commit your changes with a meaningful commit message. Please follow the [conventional commit format](https://www.conventionalcommits.org/en/v1.0.0/) if possible. 56 | 57 | ```bash 58 | git commit -m "feat: add new feature" # Use "feat" for new features 59 | ``` 60 | 61 | 8. **Push Changes** 62 | 63 | Push your changes to your forked repository: 64 | 65 | ```bash 66 | git push origin feature-or-bug-fix-name 67 | ``` 68 | 69 | 9. **Create a Pull Request (PR)** 70 | 71 | Go to the main repository and click on the "New Pull Request" button. Compare the changes between your branch and the `main` branch. Provide a clear and concise description of your changes in the PR. 72 | 73 | 10. **Review and Collaborate** 74 | 75 | Collaborate with maintainers and other contributors to address any feedback or discussions related to your PR. Be responsive to comments and make necessary changes. 76 | 77 | 11. **Merge PR** 78 | 79 | Once your PR has been approved, a maintainer will merge your changes into the main branch. 80 | 81 | 12. **Celebrate** 82 | 83 | Congratulations! You've successfully contributed to `adv-math`. Thank you for your contribution! 84 | 85 | ## Code of Conduct 86 | 87 | Please review our [Code of Conduct](CODE_OF_CONDUCT.md) before contributing to this project. We expect all contributors to adhere to these guidelines to create a positive and inclusive community. -------------------------------------------------------------------------------- /adv-math/docs/ComplexNumber.md: -------------------------------------------------------------------------------- 1 | # ComplexNumber Module 2 | 3 | The `ComplexNumber` module represents complex numbers and provides methods for performing arithmetic operations on them, including addition, subtraction, multiplication, and magnitude calculation. 4 | 5 | ## Usage 6 | 7 | To use the `ComplexNumber` module, create instances of complex numbers and use its methods in your JavaScript code. 8 | 9 | ```javascript 10 | const ComplexNumber = require('adv-math').ComplexNumber; 11 | 12 | // Create complex numbers 13 | const complex1 = new ComplexNumber(2, 3); 14 | const complex2 = new ComplexNumber(1, -1); 15 | 16 | // Example operations 17 | const sum = complex1.add(complex2); // Returns a new complex number (3, 2) 18 | const difference = complex1.subtract(complex2); // Returns a new complex number (1, 4) 19 | const product = complex1.multiply(complex2); // Returns a new complex number (5, 1) 20 | const magnitude = complex1.magnitude(); // Returns the magnitude (absolute value) of complex1 (sqrt(13)) 21 | ``` 22 | 23 | ## Constructor 24 | 25 | ### `constructor(real, imaginary)` 26 | 27 | Creates a new complex number with the specified real and imaginary parts. 28 | 29 | - `real` (number): The real part of the complex number. 30 | - `imaginary` (number): The imaginary part of the complex number. 31 | 32 | ## Methods 33 | 34 | ### `add(complex)` 35 | 36 | Adds the current complex number to another complex number and returns a new complex number representing the sum. 37 | 38 | - `complex` (ComplexNumber): The complex number to add. 39 | - Returns: A new complex number representing the sum. 40 | 41 | ### `subtract(complex)` 42 | 43 | Subtracts another complex number from the current complex number and returns a new complex number representing the difference. 44 | 45 | - `complex` (ComplexNumber): The complex number to subtract. 46 | - Returns: A new complex number representing the difference. 47 | 48 | ### `multiply(complex)` 49 | 50 | Multiplies the current complex number by another complex number and returns a new complex number representing the product. 51 | 52 | - `complex` (ComplexNumber): The complex number to multiply. 53 | - Returns: A new complex number representing the product. 54 | 55 | ### `magnitude()` 56 | 57 | Calculates and returns the magnitude (absolute value) of the complex number. 58 | 59 | - Returns: The magnitude (absolute value) of the complex number as a non-negative number. 60 | 61 | ## Examples 62 | 63 | ```javascript 64 | const ComplexNumber = require('adv-math').ComplexNumber; 65 | 66 | // Create complex numbers 67 | const complex1 = new ComplexNumber(2, 3); 68 | const complex2 = new ComplexNumber(1, -1); 69 | 70 | // Addition 71 | const sum = complex1.add(complex2); // Returns a new complex number (3, 2) 72 | 73 | // Subtraction 74 | const difference = complex1.subtract(complex2); // Returns a new complex number (1, 4) 75 | 76 | // Multiplication 77 | const product = complex1.multiply(complex2); // Returns a new complex number (5, 1) 78 | 79 | // Magnitude 80 | const magnitude1 = complex1.magnitude(); // Returns sqrt(13), approximately 3.6055 81 | const magnitude2 = complex2.magnitude(); // Returns sqrt(2), approximately 1.4142 82 | ``` -------------------------------------------------------------------------------- /adv-math/tests/linear-algebra.test.js: -------------------------------------------------------------------------------- 1 | const Matrix = require('../src/linear-algebra/matrix'); 2 | const Vector = require('../src/linear-algebra/vector'); 3 | 4 | 5 | describe('Matrix', () => { 6 | // Implicit assumption that matrix creation does not need to be tested. 7 | let matrixA; 8 | let matrixB; 9 | beforeAll(() => { 10 | matrixA = new Matrix([[1, 2], [3, 4]]); 11 | matrixB = new Matrix([[5, 6], [7, 8]]); 12 | } 13 | ); 14 | 15 | test('adds two matrices', () => { 16 | const result = matrixA.add(matrixB); 17 | expect(result.data).toEqual([[6, 8], [10, 12]]); 18 | }); 19 | 20 | test('subtracts two matrices', () => { 21 | const result = matrixA.subtract(matrixB); 22 | expect(result.data).toEqual([[-4, -4], [-4, -4]]); 23 | }); 24 | 25 | test('multiplies two matrices', () => { 26 | const result = matrixA.multiply(matrixB); 27 | expect(result.data).toEqual([[19, 22], [43, 50]]); 28 | }); 29 | 30 | test('computes trace of a matrix', () => { 31 | let result = matrixA.trace() 32 | expect(result).toEqual(5) 33 | result = matrixB.trace() 34 | expect(result).toEqual(13) 35 | }); 36 | test('throws an error for invalid matrix dimensions in addition', () => { 37 | const matrixA = new Matrix([[1,2,3],[1,2,3]]); 38 | const matrixB = new Matrix([[1,2],[1,2]]); 39 | 40 | expect(() => { 41 | matrixA.add(matrixB); 42 | }).toThrow('Matrix dimensions must match for addition.'); 43 | }); 44 | 45 | test('throws an error for invalid matrix dimensions in multiplication', () => { 46 | const matrixA = new Matrix([1,2,3],[1,2,3]); 47 | const matrixB = new Matrix([[1,2],[1,2],[1,2],[1,2]]); 48 | 49 | expect(() => { 50 | matrixA.multiply(matrixB); 51 | }).toThrow('Number of columns in the first matrix must match the number of rows in the second matrix for multiplication.'); 52 | }); 53 | }); 54 | 55 | describe('Vector', () => { 56 | const vectorA = new Vector([1, 2, 3]); 57 | const vectorB = new Vector([4, 5, 6]); 58 | test('adds two vectors', () => { 59 | const result = vectorA.add(vectorB); 60 | expect(result.components).toEqual([5, 7, 9]); 61 | }); 62 | 63 | test('subtracts two vectors', () => { 64 | const result = vectorA.subtract(vectorB); 65 | expect(result.components).toEqual([-3, -3, -3]); 66 | }); 67 | 68 | test('calculates the dot product of two vectors', () => { 69 | const result = vectorA.dot(vectorB); 70 | expect(result).toBe(32); 71 | }); 72 | 73 | test('calculates the cross product of two 3D vectors', () => { 74 | const result = vectorA.cross(vectorB); 75 | expect(result.components).toEqual([-3, 6, -3]); 76 | }); 77 | 78 | test('throws an error for invalid vector dimensions in addition', () => { 79 | const vectorB = new Vector([4, 5]); 80 | 81 | expect(() => { 82 | vectorA.add(vectorB); 83 | }).toThrow('Vector dimensions must match for addition.'); 84 | }); 85 | 86 | // Add more test cases as needed 87 | }); -------------------------------------------------------------------------------- /LEARN.md: -------------------------------------------------------------------------------- 1 | # Learning adv-math 2 | 3 | Welcome to the `adv-math` learning guide! This guide will help you get started with learning and using the `adv-math` library for advanced mathematical operations in JavaScript. 4 | 5 | ## Table of Contents 6 | 7 | - [Introduction](#introduction) 8 | - [Installation](#installation) 9 | - [Basic Usage](#basic-usage) 10 | - [Advanced Usage](#advanced-usage) 11 | - [Documentation](#documentation) 12 | - [Community and Support](#community-and-support) 13 | 14 | ## Introduction 15 | 16 | `adv-math` is a comprehensive JavaScript library designed to simplify complex mathematical calculations. It covers a wide range of mathematical topics, including basic arithmetic, complex numbers, linear algebra, statistics, geometry, trigonometry, calculus, financial calculations, units and conversions, equation solvers, and math expression parsing. 17 | 18 | Whether you are a developer, researcher, student, or enthusiast, `adv-math` provides you with powerful mathematical tools to perform various mathematical operations within your JavaScript applications. 19 | 20 | ## Installation 21 | 22 | You can install `adv-math` using either npm or yarn. Choose the package manager you prefer. 23 | 24 | ### Using npm 25 | 26 | ```bash 27 | npm install adv-math 28 | ``` 29 | 30 | ### Using yarn 31 | 32 | ```bash 33 | yarn add adv-math 34 | ``` 35 | 36 | ## Basic Usage 37 | 38 | To get started with `adv-math`, you can import the specific modules you need into your JavaScript project. Here's an example of importing and using the `BasicMath` module: 39 | 40 | ```javascript 41 | const { BasicMath } = require('adv-math'); 42 | 43 | const sum = BasicMath.add(5, 3); 44 | const product = BasicMath.multiply(4, 7); 45 | 46 | console.log('Sum:', sum); 47 | console.log('Product:', product); 48 | ``` 49 | 50 | ## Advanced Usage 51 | 52 | For more advanced mathematical operations, explore the various modules provided by `adv-math`. Each module is designed to handle specific mathematical tasks. Here's an example of using the `ComplexNumber` module to perform operations with complex numbers: 53 | 54 | ```javascript 55 | const { ComplexNumber } = require('adv-math'); 56 | 57 | const complex1 = new ComplexNumber(2, 3); 58 | const complex2 = new ComplexNumber(1, -4); 59 | const result = ComplexNumber.add(complex1, complex2); 60 | 61 | console.log('Complex Number Addition:', result.toString()); 62 | ``` 63 | 64 | ## Documentation 65 | 66 | For detailed documentation and examples of all available modules and functions, refer to the official `adv-math` documentation: 67 | 68 | [adv-math Documentation](docs/README.md) 69 | 70 | The documentation provides in-depth information on how to use each module, available functions, and usage examples. 71 | 72 | ## Community and Support 73 | 74 | - **GitHub Repository**: [adv-math GitHub](https://github.com/pb2204/advanced-math) 75 | - **Issues**: If you encounter any issues or have questions, please open an issue on the GitHub repository. 76 | - **Contributing**: We welcome contributions from the community. Check the [Contributing Guidelines](CONTRIBUTING.md) to get started. 77 | 78 | Feel free to explore the `adv-math` library and use it to solve mathematical challenges, build mathematical applications, and enhance your projects with advanced mathematical capabilities. 79 | 80 | Happy learning and coding with `adv-math`! 81 | -------------------------------------------------------------------------------- /adv-math/src/financial/financial.js: -------------------------------------------------------------------------------- 1 | class Financial { 2 | // Method to calculate the future value of an investment with compound interest 3 | static futureValue(principal, rate, time) { 4 | return principal * Math.pow(1 + rate, time); 5 | } 6 | 7 | // Method to calculate the compound interest earned on an investment 8 | static compoundInterest(principal, rate, time) { 9 | return this.futureValue(principal, rate, time) - principal; 10 | } 11 | 12 | // Method to calculate the present value of a future amount with discounting 13 | static presentValue(futureValue, rate, time) { 14 | return futureValue / Math.pow(1 + rate, time); 15 | } 16 | 17 | // Method to calculate the loan amortization schedule 18 | static loanAmortization(principal, rate, time) { 19 | const monthlyRate = rate / 12 / 100; // Monthly interest rate 20 | const numPayments = time * 12; // Number of monthly payments 21 | const monthlyPayment = (principal * monthlyRate) / (1 - Math.pow(1 + monthlyRate, -numPayments)); 22 | 23 | const amortizationSchedule = []; 24 | let remainingBalance = principal; 25 | 26 | for (let month = 1; month <= numPayments; month++) { 27 | const interestPayment = remainingBalance * monthlyRate; 28 | const principalPayment = monthlyPayment - interestPayment; 29 | remainingBalance -= principalPayment; 30 | 31 | amortizationSchedule.push({ 32 | month, 33 | monthlyPayment, 34 | principalPayment, 35 | interestPayment, 36 | remainingBalance, 37 | }); 38 | } 39 | 40 | return amortizationSchedule; 41 | } 42 | 43 | // Method to calculate the effective interest rate 44 | static effectiveInterestRate(principal, futureValue, time) { 45 | return Math.pow(futureValue / principal, 1 / time) - 1; 46 | } 47 | 48 | // Method to convert annual interest rates to monthly 49 | static annualToMonthlyInterestRate(annualRate) { 50 | return (Math.pow(1 + annualRate, 1 / 12) - 1) * 100; 51 | } 52 | 53 | // Method to calculate the net present value (NPV) of cash flows 54 | static netPresentValue(cashFlows, discountRate) { 55 | let npv = 0; 56 | for (let i = 0; i < cashFlows.length; i++) { 57 | npv += cashFlows[i] / Math.pow(1 + discountRate, i); 58 | } 59 | return npv; 60 | } 61 | 62 | // Method to adjust a value for inflation 63 | static adjustForInflation(value, inflationRate, years) { 64 | return value / Math.pow(1 + inflationRate, years); 65 | } 66 | 67 | // Method to calculate the periodic payment needed to reach a future value goal 68 | static calculateRequiredPaymentForFutureValue(futureValue, rate, time) { 69 | return futureValue / ((Math.pow(1 + rate, time) - 1) / rate); 70 | } 71 | 72 | // Method to calculate asset depreciation 73 | static calculateDepreciation(initialValue, salvageValue, usefulLife) { 74 | return (initialValue - salvageValue) / usefulLife; 75 | } 76 | 77 | // Method to calculate the total return on an investment 78 | static totalReturn(initialInvestment, finalValue, additionalInvestments) { 79 | return (finalValue - initialInvestment + additionalInvestments) / initialInvestment; 80 | } 81 | } 82 | 83 | module.exports = Financial; 84 | 85 | -------------------------------------------------------------------------------- /adv-math/src/linear-algebra/matrix.js: -------------------------------------------------------------------------------- 1 | class Matrix { 2 | data; 3 | rows; 4 | cols; 5 | 6 | constructor(list_of_lists) { 7 | this.data = list_of_lists; 8 | this.rows = list_of_lists.length; 9 | this.cols = list_of_lists[0].length; 10 | for (let i in this.rows) { 11 | let cur_col = list_of_lists[i] 12 | if (this.cols !== cur_col.length) { 13 | throw new Error('Matrix is invalid, not enough elements') 14 | } 15 | } 16 | } 17 | 18 | /** 19 | * Method to perform elementwise addition 20 | * @param {Matrix} matrixB 21 | * @return {Matrix} elementwise addition with matrixB 22 | */ 23 | add(matrixB) { 24 | if (this.rows !== matrixB.rows || this.cols !== matrixB.cols) { 25 | throw new Error('Matrix dimensions must match for addition.'); 26 | } 27 | let result = [] 28 | for (let i = 0; i < matrixB.rows; i++) { 29 | let new_arr = [] 30 | for (let j = 0; j < matrixB.cols; j++) { 31 | new_arr.push(this.data[i][j] + matrixB.data[i][j]) 32 | } 33 | result.push(new_arr) 34 | } 35 | 36 | return new Matrix(result); 37 | } 38 | 39 | /** Method to perform matrix subtraction 40 | * 41 | * @param matrixB 42 | * @returns {Matrix} elementwise subtraction with matrixB 43 | */ 44 | subtract(matrixB) { 45 | if (this.rows !== matrixB.rows || this.cols !== matrixB.cols) { 46 | throw new Error('Matrix dimensions must match for subtraction.'); 47 | } 48 | 49 | let result = [] 50 | for (let i = 0; i < matrixB.rows; i++) { 51 | let new_arr = [] 52 | for (let j = 0; j < matrixB.cols; j++) { 53 | new_arr.push(this.data[i][j] - matrixB.data[i][j]) 54 | } 55 | result.push(new_arr) 56 | } 57 | 58 | return new Matrix(result); 59 | } 60 | 61 | /** 62 | * Method to perform matrix multiplication 63 | * @param {Matrix} matrixB 64 | * @return {Matrix} Matrix multiplication with matrixB 65 | */ 66 | multiply(matrixB) { 67 | if (this.cols !== matrixB.rows) { 68 | throw new Error('Number of columns in the first matrix must match the number of rows in the second matrix for multiplication.'); 69 | } 70 | 71 | let result = [] 72 | for (let i = 0; i < matrixB.rows; i++) { 73 | let new_arr = [] 74 | for (let j = 0; j < matrixB.cols; j++) { 75 | let sum = 0; 76 | for (let k = 0; k < this.cols; k++) { 77 | sum += this.data[i][k] * matrixB.data[k][j]; 78 | } 79 | new_arr.push(sum); 80 | } 81 | result.push(new_arr) 82 | } 83 | 84 | return new Matrix(result); 85 | } 86 | 87 | /** 88 | * Method to calculate the trace of a square matrix 89 | * @returns {number} the trace 90 | */ 91 | trace() { 92 | if (this.rows !== this.cols) { 93 | throw new Error('Matrix is not square, Trace does not exist.') 94 | } 95 | let result = 0; 96 | for (let i = 0; i < this.rows; i++) { 97 | result += this.data[i][i] 98 | } 99 | return result 100 | } 101 | 102 | } 103 | 104 | module.exports = Matrix; 105 | -------------------------------------------------------------------------------- /adv-math/src/geometry-trigonometry/geometry.js: -------------------------------------------------------------------------------- 1 | class Geometry { 2 | // Method to calculate the area of a rectangle 3 | static rectangleArea(length, width) { 4 | return length * width; 5 | } 6 | 7 | // Method to calculate the perimeter of a rectangle 8 | static rectanglePerimeter(length, width) { 9 | return 2 * (length + width); 10 | } 11 | 12 | // Method to calculate the area of a circle 13 | static circleArea(radius) { 14 | return Math.PI * Math.pow(radius, 2); 15 | } 16 | 17 | // Method to calculate the circumference of a circle 18 | static circleCircumference(radius) { 19 | return 2 * Math.PI * radius; 20 | } 21 | 22 | // Method to calculate the area of a triangle given base and height 23 | static triangleArea(base, height) { 24 | return (base * height) / 2; 25 | } 26 | 27 | // Method to calculate the volume of a sphere given its radius 28 | static sphereVolume(radius) { 29 | return (4 / 3) * Math.PI * Math.pow(radius, 3); 30 | } 31 | 32 | // Method to calculate the area of an equilateral triangle given its side length 33 | static equilateralTriangleArea(side) { 34 | return (Math.sqrt(3) / 4) * Math.pow(side, 2); 35 | } 36 | //Method to calulate the area of the triangle given its side lengths 37 | static triangleArea_sides(side1, side2, side3) { 38 | const s = (side1 + side2 + side3) / 2; 39 | return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3)); 40 | } 41 | //Method to calulate the area of a square given its side length 42 | static squareArea(side) { 43 | return Math.pow(side, 2); 44 | } 45 | //Method to calculate the perimeter of a square given its side length 46 | static squarePerimeter(side) { 47 | return 4 * side; 48 | } 49 | 50 | // Method to calculate the volume of a cube given its side length 51 | static cubeVolume(side) { 52 | return Math.pow(side, 3); 53 | } 54 | 55 | // Method to calculate the volume of a rectangular prism given length, width, and height 56 | static rectangularPrismVolume(length, width, height) { 57 | return length * width * height; 58 | } 59 | 60 | // Method to calculate the surface area of a rectangular prism given length, width, and height 61 | static rectangularPrismSurfaceArea(length, width, height) { 62 | return 2 * (length * width + width * height + height * length); 63 | } 64 | 65 | // Method to calculate the volume of a cylinder given its radius and height 66 | static cylinderVolume(radius, height) { 67 | return Math.PI * Math.pow(radius, 2) * height; 68 | } 69 | 70 | // Method to calculate the surface area of a cylinder given its radius and height 71 | static cylinderSurfaceArea(radius, height) { 72 | const baseArea = Math.PI * Math.pow(radius, 2); 73 | const lateralArea = 2 * Math.PI * radius * height; 74 | return 2 * baseArea + lateralArea; 75 | } 76 | 77 | // Method to calculate the volume of a cone given its radius and height 78 | static coneVolume(radius, height) { 79 | return (1 / 3) * Math.PI * Math.pow(radius, 2) * height; 80 | } 81 | 82 | // Method to calculate the surface area of a cone given its radius and height 83 | static coneSurfaceArea(radius, height) { 84 | const slantHeight = Math.sqrt(Math.pow(radius, 2) + Math.pow(height, 2)); 85 | const baseArea = Math.PI * Math.pow(radius, 2); 86 | const lateralArea = Math.PI * radius * slantHeight; 87 | return baseArea + lateralArea; 88 | } 89 | } 90 | 91 | module.exports = Geometry; 92 | -------------------------------------------------------------------------------- /adv-math/tests/geometry-trigonometry.test.js: -------------------------------------------------------------------------------- 1 | const Geometry = require('../src/geometry-trigonometry/geometry'); 2 | const Trigonometry = require('../src/geometry-trigonometry/trigonometry'); 3 | 4 | describe('Geometry', () => { 5 | test('calculates the area of a rectangle', () => { 6 | expect(Geometry.rectangleArea(4, 5)).toBe(20); 7 | }); 8 | 9 | test('calculates the perimeter of a rectangle', () => { 10 | expect(Geometry.rectanglePerimeter(4, 5)).toBe(18); 11 | }); 12 | 13 | test('calculates the area of a circle', () => { 14 | expect(Geometry.circleArea(3)).toBeCloseTo(28.274, 3); 15 | }); 16 | 17 | test('calculates the circumference of a circle', () => { 18 | expect(Geometry.circleCircumference(3)).toBeCloseTo(18.850, 3); 19 | }); 20 | test('calculates the area of a triangle', () => { 21 | expect(Geometry.triangleArea(3, 4)).toBe(6); 22 | }); 23 | test('calculates the volume of a sphere', () => { 24 | expect(Geometry.sphereVolume(3)).toBeCloseTo(113.097, 3); 25 | }); 26 | test('calculates the area of an equilateral triangle', () => { 27 | expect(Geometry.equilateralTriangleArea(3)).toBeCloseTo(3.897, 3); 28 | }); 29 | test('calculates the area of a triangle given its side lengths', () => { 30 | expect(Geometry.triangleArea_sides(3, 4, 5)).toBe(6); 31 | }); 32 | test('calculates the area of a square given its side length', () => { 33 | expect(Geometry.squareArea(3)).toBe(9); 34 | }); 35 | test('calculates the perimeter of a square given its side length', () => { 36 | expect(Geometry.squarePerimeter(3)).toBe(12); 37 | }); 38 | test('calculates the volume of a cube given its side length', () => { 39 | expect(Geometry.cubeVolume(3)).toBe(27); 40 | }); 41 | test('calculates the volume of a rectangular prism given length, width, and height', () => { 42 | expect(Geometry.rectangularPrismVolume(3, 4, 5)).toBe(60); 43 | }); 44 | test('calculates the surface area of a rectangular prism given length, width, and height', () => { 45 | expect(Geometry.rectangularPrismSurfaceArea(3, 4, 5)).toBe(94); 46 | }); 47 | test('calculates the volume of a cylinder given radius and height', () => { 48 | expect(Geometry.cylinderVolume(3, 5)).toBeCloseTo(141.371, 3); 49 | }); 50 | test('calculates the surface area of a cylinder given radius and height', () => { 51 | expect(Geometry.cylinderSurfaceArea(3, 5)).toBeCloseTo(150.796, 3); 52 | }); 53 | test('calculates the volume of a cone given radius and height', () => { 54 | expect(Geometry.coneVolume(3, 5)).toBeCloseTo(47.123, 3); 55 | }); 56 | test('calculates the surface area of a cone given radius and height', () => { 57 | expect(Geometry.coneSurfaceArea(3, 5)).toBeCloseTo(83.229, 3); 58 | }); 59 | // Add more test cases as needed 60 | }); 61 | 62 | describe('Trigonometry', () => { 63 | test('calculates the sine of an angle in degrees', () => { 64 | expect(Trigonometry.sine(30)).toBeCloseTo(0.5, 3); 65 | }); 66 | 67 | test('calculates the cosine of an angle in degrees', () => { 68 | expect(Trigonometry.cosine(45)).toBeCloseTo(0.707, 3); 69 | }); 70 | 71 | test('calculates the tangent of an angle in degrees', () => { 72 | expect(Trigonometry.tangent(60)).toBeCloseTo(1.732, 3); 73 | }); 74 | 75 | test('calculates the cosecant of an angle in degrees', () => { 76 | expect(Trigonometry.cosecant(30)).toBeCloseTo(2, 3); 77 | }); 78 | 79 | test('calculates the secant of an angle in degrees', () => { 80 | expect(Trigonometry.secant(45)).toBeCloseTo(1.414, 3); 81 | }); 82 | 83 | test('calculates the cotangent of an angle in degrees', () => { 84 | expect(Trigonometry.cotangent(60)).toBeCloseTo(0.577, 3); 85 | }); 86 | 87 | test('calculates the arcsine of a value', () => { 88 | expect(Trigonometry.arcsine(0.5)).toBeCloseTo(30, 3); 89 | }); 90 | 91 | // Add more test cases as needed 92 | }); -------------------------------------------------------------------------------- /adv-math/src/expression-evaluator/expression-evaluator.js: -------------------------------------------------------------------------------- 1 | // adv-math/src/expression-evaluator/expression-evaluator.js 2 | 3 | class ExpressionEvaluator { 4 | static evaluateExpression(expression) { 5 | function isOperator(char) { 6 | return ['+', '-', '*', '/'].includes(char); 7 | } 8 | 9 | function applyOperator(operators, values) { 10 | const operator = operators.pop(); 11 | const right = values.pop(); 12 | const left = values.pop(); 13 | 14 | switch (operator) { 15 | case '+': 16 | values.push(left + right); 17 | break; 18 | case '-': 19 | values.push(left - right); 20 | break; 21 | case '*': 22 | values.push(left * right); 23 | break; 24 | case '/': 25 | if (right === 0) { 26 | throw new Error('Division by zero'); 27 | } 28 | values.push(left / right); 29 | break; 30 | default: 31 | throw new Error('Invalid operator'); 32 | } 33 | } 34 | 35 | const operators = []; 36 | const values = []; 37 | 38 | const precedence = { 39 | '+': 1, 40 | '-': 1, 41 | '*': 2, 42 | '/': 2, 43 | }; 44 | 45 | let i = 0; 46 | while (i < expression.length) { 47 | const char = expression[i]; 48 | 49 | console.log(`Character: ${char}`); 50 | console.log(`Operators: ${operators.join(', ')}`); 51 | console.log(`Values: ${values.join(', ')}`); 52 | 53 | if (char === '(') { 54 | operators.push(char); 55 | } else if (char === ')') { 56 | while (operators.length > 0 && operators[operators.length - 1] !== '(') { 57 | applyOperator(operators, values); 58 | } 59 | if (operators.length === 0 || operators.pop() !== '(') { 60 | console.error(`Mismatched parentheses in expression: ${expression}`); 61 | throw new Error('Mismatched parentheses'); 62 | } 63 | } else if (isOperator(char)) { 64 | while ( 65 | operators.length > 0 && 66 | isOperator(operators[operators.length - 1]) && 67 | precedence[operators[operators.length - 1]] >= precedence[char] 68 | ) { 69 | applyOperator(operators, values); 70 | } 71 | operators.push(char); 72 | } else if (!isNaN(char) || char === '.') { 73 | let num = ''; 74 | while (i < expression.length && (!isNaN(expression[i]) || expression[i] === '.')) { 75 | num += expression[i]; 76 | i++; 77 | } 78 | i--; // Move back one step since the loop will increment it again 79 | values.push(parseFloat(num)); 80 | } else { 81 | console.error(`Invalid character '${char}' in expression: ${expression}`); 82 | throw new Error('Invalid character: ' + char); 83 | } 84 | 85 | i++; // Move to the next character 86 | } 87 | 88 | console.log(`Final Operators: ${operators.join(', ')}`); 89 | console.log(`Final Values: ${values.join(', ')}`); 90 | 91 | while (operators.length > 0) { 92 | applyOperator(operators, values); 93 | } 94 | 95 | if (values.length !== 1 || operators.length !== 0) { 96 | console.error(`Invalid expression: ${expression}`); 97 | throw new Error('Invalid expression'); 98 | } 99 | 100 | return values[0]; 101 | } 102 | } 103 | 104 | module.exports = ExpressionEvaluator; 105 | -------------------------------------------------------------------------------- /adv-math/src/geometry-trigonometry/trigonometry.js: -------------------------------------------------------------------------------- 1 | class Trigonometry { 2 | // Method to calculate the sine of an angle in degrees 3 | static sine(degrees) { 4 | const radians = (degrees * Math.PI) / 180; 5 | return Math.sin(radians); 6 | } 7 | 8 | // Method to calculate the cosine of an angle in degrees 9 | static cosine(degrees) { 10 | const radians = (degrees * Math.PI) / 180; 11 | return Math.cos(radians); 12 | } 13 | 14 | // Method to calculate the tangent of an angle in degrees 15 | static tangent(degrees) { 16 | const radians = (degrees * Math.PI) / 180; 17 | return Math.tan(radians); 18 | } 19 | 20 | // Method to calculate the cosecant of an angle in degrees 21 | static cosecant(degrees) { 22 | return 1 / this.sine(degrees); 23 | } 24 | 25 | // Method to calculate the secant of an angle in degrees 26 | static secant(degrees) { 27 | return 1 / this.cosine(degrees); 28 | } 29 | 30 | // Method to calculate the cotangent of an angle in degrees 31 | static cotangent(degrees) { 32 | return 1 / this.tangent(degrees); 33 | } 34 | 35 | // Method to calculate the arcsine in degrees 36 | static arcsine(value) { 37 | if (value < -1 || value > 1) { 38 | throw new Error('Invalid input for arcsine.'); 39 | } 40 | const radians = Math.asin(value); 41 | return (radians * 180) / Math.PI; 42 | } 43 | 44 | // Method to calculate the arccosine in degrees 45 | static arccosine(value) { 46 | if (value < -1 || value > 1) { 47 | throw new Error('Invalid input for arccosine.'); 48 | } 49 | const radians = Math.acos(value); 50 | return (radians * 180) / Math.PI; 51 | } 52 | 53 | // Method to calculate the arctangent in degrees 54 | static arctangent(value) { 55 | const radians = Math.atan(value); 56 | return (radians * 180) / Math.PI; 57 | } 58 | 59 | // Method to calculate the arccosecant in degrees 60 | static arccosecant(value) { 61 | if (value === 0) { 62 | throw new Error('Invalid input for arccosecant.'); 63 | } 64 | return this.arcsine(1 / value); 65 | } 66 | 67 | // Method to calculate the arcsecant in degrees 68 | static arcsecant(value) { 69 | if (value === 0) { 70 | throw new Error('Invalid input for arcsecant.'); 71 | } 72 | return this.arccosine(1 / value); 73 | } 74 | 75 | // Method to calculate the arccotangent in degrees 76 | static arccotangent(value) { 77 | if (value === 0) { 78 | throw new Error('Invalid input for arccotangent.'); 79 | } 80 | return this.arctangent(1 / value); 81 | } 82 | 83 | // Method to calculate the hyperbolic sine of an angle in degrees 84 | static sinh(degrees) { 85 | const radians = (degrees * Math.PI) / 180; 86 | return Math.sinh(radians); 87 | } 88 | 89 | // Method to calculate the hyperbolic cosine of an angle in degrees 90 | static cosh(degrees) { 91 | const radians = (degrees * Math.PI) / 180; 92 | return Math.cosh(radians); 93 | } 94 | 95 | // Method to calculate the hyperbolic tangent of an angle in degrees 96 | static tanh(degrees) { 97 | const radians = (degrees * Math.PI) / 180; 98 | return Math.tanh(radians); 99 | } 100 | 101 | // Method to calculate the hyperbolic arcsine in degrees 102 | static arsinh(value) { 103 | const result = Math.asinh(value); 104 | return (result * 180) / Math.PI; 105 | } 106 | 107 | // Method to calculate the hyperbolic arccosine in degrees 108 | static arcosh(value) { 109 | if (value < 1) { 110 | throw new Error('Invalid input for arcosh.'); 111 | } 112 | const result = Math.acosh(value); 113 | return (result * 180) / Math.PI; 114 | } 115 | 116 | // Method to calculate the hyperbolic arctangent in degrees 117 | static artanh(value) { 118 | if (value < -1 || value > 1) { 119 | throw new Error('Invalid input for artanh.'); 120 | } 121 | const result = Math.atanh(value); 122 | return (result * 180) / Math.PI; 123 | } 124 | } 125 | 126 | module.exports = Trigonometry; 127 | -------------------------------------------------------------------------------- /adv-math/docs/Trigonometry.md: -------------------------------------------------------------------------------- 1 | # Trigonometry Module 2 | 3 | The `Trigonometry` module provides methods for performing trigonometric calculations, including sine, cosine, tangent, and their inverse functions. 4 | 5 | ## Usage 6 | 7 | To use the `Trigonometry` module, import it and use its methods in your JavaScript code. 8 | 9 | ```javascript 10 | const Trigonometry = require('adv-math').Trigonometry; 11 | 12 | // Example usage 13 | const degrees = 30; 14 | 15 | // Calculate sine, cosine, and tangent 16 | const sineValue = Trigonometry.sine(degrees); 17 | const cosineValue = Trigonometry.cosine(degrees); 18 | const tangentValue = Trigonometry.tangent(degrees); 19 | 20 | // Calculate arcsine, arccosine, and arctangent 21 | const arcsineValue = Trigonometry.arcsine(0.5); 22 | const arccosineValue = Trigonometry.arccosine(0.5); 23 | const arctangentValue = Trigonometry.arctangent(0.577); 24 | 25 | // Calculate cosecant, secant, and cotangent 26 | const cosecantValue = Trigonometry.cosecant(degrees); 27 | const secantValue = Trigonometry.secant(degrees); 28 | const cotangentValue = Trigonometry.cotangent(degrees); 29 | 30 | // Calculate arccosecant, arcsecant, and arccotangent 31 | const arccosecantValue = Trigonometry.arccosecant(2); 32 | const arcsecantValue = Trigonometry.arcsecant(2); 33 | const arccotangentValue = Trigonometry.arccotangent(1.732); 34 | ``` 35 | 36 | ## Methods 37 | 38 | ### `sine(degrees)` 39 | 40 | Calculates the sine of an angle in degrees. 41 | 42 | - `degrees` (number): The angle in degrees. 43 | - Returns: The sine value of the angle. 44 | 45 | ### `cosine(degrees)` 46 | 47 | Calculates the cosine of an angle in degrees. 48 | 49 | - `degrees` (number): The angle in degrees. 50 | - Returns: The cosine value of the angle. 51 | 52 | ### `tangent(degrees)` 53 | 54 | Calculates the tangent of an angle in degrees. 55 | 56 | - `degrees` (number): The angle in degrees. 57 | - Returns: The tangent value of the angle. 58 | 59 | ### `cosecant(degrees)` 60 | 61 | Calculates the cosecant of an angle in degrees. 62 | 63 | - `degrees` (number): The angle in degrees. 64 | - Returns: The cosecant value of the angle. 65 | 66 | ### `secant(degrees)` 67 | 68 | Calculates the secant of an angle in degrees. 69 | 70 | - `degrees` (number): The angle in degrees. 71 | - Returns: The secant value of the angle. 72 | 73 | ### `cotangent(degrees)` 74 | 75 | Calculates the cotangent of an angle in degrees. 76 | 77 | - `degrees` (number): The angle in degrees. 78 | - Returns: The cotangent value of the angle. 79 | 80 | ### `arcsine(value)` 81 | 82 | Calculates the arcsine (inverse sine) in degrees. 83 | 84 | - `value` (number): The value for which to calculate arcsine. Should be between -1 and 1. 85 | - Returns: The arcsine value in degrees. 86 | 87 | ### `arccosine(value)` 88 | 89 | Calculates the arccosine (inverse cosine) in degrees. 90 | 91 | - `value` (number): The value for which to calculate arccosine. Should be between -1 and 1. 92 | - Returns: The arccosine value in degrees. 93 | 94 | ### `arctangent(value)` 95 | 96 | Calculates the arctangent (inverse tangent) in degrees. 97 | 98 | - `value` (number): The value for which to calculate arctangent. 99 | - Returns: The arctangent value in degrees. 100 | 101 | ### `arccosecant(value)` 102 | 103 | Calculates the arccosecant (inverse cosecant) in degrees. 104 | 105 | - `value` (number): The value for which to calculate arccosecant. Should not be 0. 106 | - Returns: The arccosecant value in degrees. 107 | 108 | ### `arcsecant(value)` 109 | 110 | Calculates the arcsecant (inverse secant) in degrees. 111 | 112 | - `value` (number): The value for which to calculate arcsecant. Should not be 0. 113 | - Returns: The arcsecant value in degrees. 114 | 115 | ### `arccotangent(value)` 116 | 117 | Calculates the arccotangent (inverse cotangent) in degrees. 118 | 119 | - `value` (number): The value for which to calculate arccotangent. Should not be 0. 120 | - Returns: The arccotangent value in degrees. 121 | 122 | ## Examples 123 | 124 | ```javascript 125 | const Trigonometry = require('adv-math').Trigonometry; 126 | 127 | // Example calculations 128 | const degrees = 30; 129 | 130 | const sineValue = Trigonometry.sine(degrees); // Returns 0.5 131 | const cosineValue = Trigonometry.cosine(degrees); // Returns 0.86602540378 132 | const tangentValue = Trigonometry.tangent(degrees); // Returns 0.57735026919 133 | 134 | const arcsineValue = Trigonometry.arcsine(0.5); // Returns 30 135 | const arccosineValue = Trigonometry.arccosine(0.5); // Returns 60 136 | const arctangentValue = Trigonometry.arctangent(0.577); // Returns 30 137 | 138 | const cosecantValue = Trigonometry.cosecant(degrees); // Returns 2 139 | const secantValue = Trigonometry.secant(degrees); // Returns 1.15470053838 140 | const cotangentValue = Trigonometry.cotangent(degrees); // Returns 1.73205080757 141 | 142 | const arccosecantValue = Trigonometry.arccosecant(2); // Returns 30 143 | const arcsecantValue = Trigonometry.arcsecant(2); // Returns 60 144 | const arccotangentValue = Trigonometry.arccotangent(1.732); // Returns 30 145 | ``` 146 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Advanced Math (adv-math) 2 | 3 | Advanced Mathematical Operations Library for JavaScript 4 | 5 | - [Description](#description) 6 | - [Installation](#installation) 7 | - [NPM](#npm-installation) 8 | - [Yarn](#yarn-installation) 9 | - [Motive](#motive) 10 | - [Practical Usage](#practical-usage) 11 | - [Example Usage](#example-usage) 12 | - [BasicMath](#basicmath) 13 | - [ComplexNumber](#complexnumber) 14 | - [Matrix](#matrix) 15 | - [Vector](#vector) 16 | - [Statistics](#statistics) 17 | - [Geometry](#geometry) 18 | - [Trigonometry](#trigonometry) 19 | - [Calculus](#calculus) 20 | - [Financial](#financial) 21 | - [Units](#units) 22 | - [Equations](#equations) 23 | - [Parser](#parser) 24 | - [Random](#random) 25 | - [Expression Evaluator](#expression-evaluator) 26 | - [License](#license) 27 | - [Code of Conduct](#code-of-conduct) 28 | - [Contributing](#contributing) 29 | - [Learn More](#learn-more) 30 | - [Developer Details](#developer-details) 31 | - [Happy Coding](#happy-coding) 32 | 33 | 34 | ## Description 35 | 36 | `adv-math` is a comprehensive JavaScript library that simplifies advanced mathematical calculations, covering a wide range of mathematical topics such as basic arithmetic, complex numbers, linear algebra, statistics, geometry, trigonometry, calculus, financial calculations, units and conversions, equation solvers, and math expression parsing. This library is designed to provide developers with powerful mathematical tools for various applications. 37 | 38 | **New Feature:** 39 | - Added `Expression Evaluator` for evaluating complex mathematical expressions. See [Expression Evaluator](#expression-evaluator) below for details. 40 | 41 | 42 | ## Installation 43 | 44 | ### NPM Installation 45 | 46 | You can install `adv-math` using NPM: 47 | 48 | ```bash 49 | npm install adv-math 50 | ``` 51 | 52 | ### Yarn Installation 53 | 54 | Alternatively, you can install it using Yarn: 55 | 56 | ```bash 57 | yarn add adv-math 58 | ``` 59 | 60 | 61 | ## Motive 62 | 63 | The primary motive of this project is to simplify complex mathematical operations for developers, researchers, and students. It aims to provide a user-friendly, efficient, and well-documented library for performing advanced mathematical calculations in JavaScript. 64 | 65 | 66 | ## Practical Usage 67 | 68 | `adv-math` can be used in a wide range of practical scenarios, including but not limited to: 69 | 70 | - Scientific research and analysis 71 | - Engineering and physics simulations 72 | - Financial modeling and analysis 73 | - Game development for physics and mathematics-based simulations 74 | - Educational applications for teaching and learning mathematics 75 | - Data analysis and statistics 76 | - Geometric calculations for graphics and CAD applications 77 | - Solving equations and parsing mathematical expressions 78 | 79 | 80 | ## Example Usage 81 | 82 | Here's an overview of how to use some of the key modules in Advanced Math: 83 | ### BasicMath 84 | 85 | ```javascript 86 | const { BasicMath } = require('adv-math'); 87 | 88 | const sum = BasicMath.add(5, 3); // 8 89 | const product = BasicMath.multiply(4, 6); // 24 90 | ``` 91 | 92 | ### ComplexNumber 93 | 94 | ```javascript 95 | const { ComplexNumber } = require('adv-math'); 96 | 97 | const num1 = new ComplexNumber(2, 3); 98 | const num2 = new ComplexNumber(1, -1); 99 | 100 | const result = ComplexNumber.add(num1, num2); // (3, 2) 101 | ``` 102 | 103 | ### Matrix 104 | 105 | ```javascript 106 | const { Matrix } = require('adv-math'); 107 | 108 | const matrix1 = new Matrix([[1, 2], [3, 4]]); 109 | const matrix2 = new Matrix([[5, 6], [7, 8]]); 110 | 111 | const product = matrix1.multiply(matrix2); // [[19, 22], [43, 50]] 112 | ``` 113 | 114 | ### Vector 115 | 116 | ```javascript 117 | const { Vector } = require('adv-math'); 118 | 119 | const vector1 = new Vector([1, 2, 3]); 120 | const vector2 = new Vector([4, 5, 6]); 121 | 122 | const dotProduct = Vector.dot(vector1, vector2); // 32 123 | ``` 124 | 125 | ### Statistics 126 | 127 | ```javascript 128 | const { Statistics } = require('adv-math'); 129 | 130 | const data = [2, 4, 6, 8, 10]; 131 | const mean = Statistics.mean(data); // 6 132 | const variance = Statistics.variance(data); // 8 133 | ``` 134 | 135 | ### Geometry 136 | 137 | ```javascript 138 | const { Geometry } = require('adv-math'); 139 | 140 | const area = Geometry.calculateArea(5); // Calculate the area of a circle with radius 5 141 | const perimeter = Geometry.calculatePerimeter(7); // Calculate the perimeter of a rectangle with width 7 142 | ``` 143 | 144 | ### Trigonometry 145 | 146 | ```javascript 147 | const { Trigonometry } = require('adv-math'); 148 | 149 | const sine = Trigonometry.sin(30); // Calculate the sine of 30 degrees 150 | const cosine = Trigonometry.cos(45); // Calculate the cosine of 45 degrees 151 | ``` 152 | 153 | ### Calculus 154 | 155 | ```javascript 156 | const { Calculus } = require('adv-math'); 157 | 158 | const derivative = Calculus.derivative('2 * x^2 + 3 * x', 'x'); // Calculate the derivative of the function 159 | const integral = Calculus.integral('4 * x^3 + 2 * x', 'x'); // Calculate the integral of the function 160 | ``` 161 | 162 | ### Financial 163 | 164 | ```javascript 165 | const { Financial } = require('adv-math'); 166 | 167 | const futureValue = Financial.futureValue(1000, 0.05, 5); // Calculate the future value of an investment 168 | const presentValue = Financial.presentValue(1500, 0.08, 3); // Calculate the present value of a sum of money 169 | ``` 170 | 171 | ### Units 172 | 173 | ```javascript 174 | const { Units } = require('adv-math'); 175 | 176 | const metersToFeet = Units.convert(5, 'meters', 'feet'); // Convert 5 meters to feet 177 | const poundsToKilograms = Units.convert(150, 'pounds', 'kilograms'); // Convert 150 pounds to kilograms 178 | ``` 179 | 180 | ### Equations 181 | 182 | ```javascript 183 | const { Equations } = require('adv-math'); 184 | 185 | const root = Equations.solveQuadratic(1, -3, 2); // Solve the quadratic equation x^2 - 3x + 2 = 0 186 | ``` 187 | 188 | ### Parser 189 | 190 | ```javascript 191 | const { Parser } = require('adv-math'); 192 | 193 | const expression = '2 + 3 * (4 - 1)'; 194 | const result = Parser.parseExpression(expression); // Parse and evaluate the expression 195 | ``` 196 | 197 | ### Random 198 | 199 | ```javascript 200 | const { Random } = require('adv-math'); 201 | 202 | const randomInteger = Random.randomInt(1, 10); // Generate a random integer between 1 and 10 203 | const randomFloat = Random.randomFloat(0, 1); // Generate a random floating-point number between 0 and 1 204 | ``` 205 | 206 | ### Expression Evaluator 207 | 208 | ```javascript 209 | const { ExpressionEvaluator } = require('adv-math'); 210 | 211 | const expression = '2 + 3 * (4 - 1)'; 212 | const result = ExpressionEvaluator.evaluateExpression(expression); // Evaluate the mathematical expression 213 | console.log('Result:', result); // Output: 11 214 | ``` 215 | ## License 216 | 217 | This project is licensed under the [MIT License](LICENSE). 218 | 219 | 220 | ## Code of Conduct 221 | 222 | Please read our [Code of Conduct](CODE_OF_CONDUCT.md) to understand the standards and expectations for participating in this community. 223 | 224 | 225 | ## Contributing 226 | 227 | We welcome contributions! Please check our [Contributing Guidelines](CONTRIBUTING.md) for details on how to contribute to this project. 228 | 229 | 230 | ## Learn More 231 | 232 | For detailed documentation and usage examples, visit our [documentation](docs/). 233 | 234 | 235 | ## Developer Details 236 | 237 | - **Author:** [Pabitra Banerjee](https://pabitrabanerjee.me) 238 | - **Email:** [Pabitra Banerjee](mailto:rockstarpabitra2204@gmail.com) 239 | - **GitHub:** [PB2204](https://github.com/PB2204) 240 | 241 | 242 | ## Happy Coding 🚀 243 | 244 | We hope you find `adv-math` useful for your mathematical projects and applications. Happy coding! 245 | -------------------------------------------------------------------------------- /adv-math/README.md: -------------------------------------------------------------------------------- 1 | # Advanced Math (adv-math) 2 | 3 | Advanced Mathematical Operations Library for JavaScript 4 | 5 | - [Description](#description) 6 | - [Installation](#installation) 7 | - [NPM](#npm-installation) 8 | - [Yarn](#yarn-installation) 9 | - [Motive](#motive) 10 | - [Practical Usage](#practical-usage) 11 | - [Example Usage](#example-usage) 12 | - [BasicMath](#basicmath) 13 | - [ComplexNumber](#complexnumber) 14 | - [Matrix](#matrix) 15 | - [Vector](#vector) 16 | - [Statistics](#statistics) 17 | - [Geometry](#geometry) 18 | - [Trigonometry](#trigonometry) 19 | - [Calculus](#calculus) 20 | - [Financial](#financial) 21 | - [Units](#units) 22 | - [Equations](#equations) 23 | - [Parser](#parser) 24 | - [Random](#random) 25 | - [Expression Evaluator](#expression-evaluator) 26 | - [License](#license) 27 | - [Code of Conduct](#code-of-conduct) 28 | - [Contributing](#contributing) 29 | - [Learn More](#learn-more) 30 | - [Developer Details](#developer-details) 31 | - [Happy Coding](#happy-coding) 32 | 33 | 34 | ## Description 35 | 36 | `adv-math` is a comprehensive JavaScript library that simplifies advanced mathematical calculations, covering a wide range of mathematical topics such as basic arithmetic, complex numbers, linear algebra, statistics, geometry, trigonometry, calculus, financial calculations, units and conversions, equation solvers, and math expression parsing. This library is designed to provide developers with powerful mathematical tools for various applications. 37 | 38 | **New Feature:** 39 | - Added `Expression Evaluator` for evaluating complex mathematical expressions. See [Expression Evaluator](#expression-evaluator) below for details. 40 | 41 | 42 | ## Installation 43 | 44 | ### NPM Installation 45 | 46 | You can install `adv-math` using NPM: 47 | 48 | ```bash 49 | npm install adv-math 50 | ``` 51 | 52 | ### Yarn Installation 53 | 54 | Alternatively, you can install it using Yarn: 55 | 56 | ```bash 57 | yarn add adv-math 58 | ``` 59 | 60 | 61 | ## Motive 62 | 63 | The primary motive of this project is to simplify complex mathematical operations for developers, researchers, and students. It aims to provide a user-friendly, efficient, and well-documented library for performing advanced mathematical calculations in JavaScript. 64 | 65 | 66 | ## Practical Usage 67 | 68 | `adv-math` can be used in a wide range of practical scenarios, including but not limited to: 69 | 70 | - Scientific research and analysis 71 | - Engineering and physics simulations 72 | - Financial modeling and analysis 73 | - Game development for physics and mathematics-based simulations 74 | - Educational applications for teaching and learning mathematics 75 | - Data analysis and statistics 76 | - Geometric calculations for graphics and CAD applications 77 | - Solving equations and parsing mathematical expressions 78 | 79 | 80 | ## Example Usage 81 | 82 | Here's an overview of how to use some of the key modules in Advanced Math: 83 | ### BasicMath 84 | 85 | ```javascript 86 | const { BasicMath } = require('adv-math'); 87 | 88 | const sum = BasicMath.add(5, 3); // 8 89 | const product = BasicMath.multiply(4, 6); // 24 90 | ``` 91 | 92 | ### ComplexNumber 93 | 94 | ```javascript 95 | const { ComplexNumber } = require('adv-math'); 96 | 97 | const num1 = new ComplexNumber(2, 3); 98 | const num2 = new ComplexNumber(1, -1); 99 | 100 | const result = ComplexNumber.add(num1, num2); // (3, 2) 101 | ``` 102 | 103 | ### Matrix 104 | 105 | ```javascript 106 | const { Matrix } = require('adv-math'); 107 | 108 | const matrix1 = new Matrix([[1, 2], [3, 4]]); 109 | const matrix2 = new Matrix([[5, 6], [7, 8]]); 110 | 111 | const product = Matrix.multiply(matrix1, matrix2); // [[19, 22], [43, 50]] 112 | ``` 113 | 114 | ### Vector 115 | 116 | ```javascript 117 | const { Vector } = require('adv-math'); 118 | 119 | const vector1 = new Vector([1, 2, 3]); 120 | const vector2 = new Vector([4, 5, 6]); 121 | 122 | const dotProduct = Vector.dot(vector1, vector2); // 32 123 | ``` 124 | 125 | ### Statistics 126 | 127 | ```javascript 128 | const { Statistics } = require('adv-math'); 129 | 130 | const data = [2, 4, 6, 8, 10]; 131 | const mean = Statistics.mean(data); // 6 132 | const variance = Statistics.variance(data); // 8 133 | ``` 134 | 135 | ### Geometry 136 | 137 | ```javascript 138 | const { Geometry } = require('adv-math'); 139 | 140 | const area = Geometry.calculateArea(5); // Calculate the area of a circle with radius 5 141 | const perimeter = Geometry.calculatePerimeter(7); // Calculate the perimeter of a rectangle with width 7 142 | ``` 143 | 144 | ### Trigonometry 145 | 146 | ```javascript 147 | const { Trigonometry } = require('adv-math'); 148 | 149 | const sine = Trigonometry.sin(30); // Calculate the sine of 30 degrees 150 | const cosine = Trigonometry.cos(45); // Calculate the cosine of 45 degrees 151 | ``` 152 | 153 | ### Calculus 154 | 155 | ```javascript 156 | const { Calculus } = require('adv-math'); 157 | 158 | const derivative = Calculus.derivative('2 * x^2 + 3 * x', 'x'); // Calculate the derivative of the function 159 | const integral = Calculus.integral('4 * x^3 + 2 * x', 'x'); // Calculate the integral of the function 160 | ``` 161 | 162 | ### Financial 163 | 164 | ```javascript 165 | const { Financial } = require('adv-math'); 166 | 167 | const futureValue = Financial.futureValue(1000, 0.05, 5); // Calculate the future value of an investment 168 | const presentValue = Financial.presentValue(1500, 0.08, 3); // Calculate the present value of a sum of money 169 | ``` 170 | 171 | ### Units 172 | 173 | ```javascript 174 | const { Units } = require('adv-math'); 175 | 176 | const metersToFeet = Units.convert(5, 'meters', 'feet'); // Convert 5 meters to feet 177 | const poundsToKilograms = Units.convert(150, 'pounds', 'kilograms'); // Convert 150 pounds to kilograms 178 | ``` 179 | 180 | ### Equations 181 | 182 | ```javascript 183 | const { Equations } = require('adv-math'); 184 | 185 | const root = Equations.solveQuadratic(1, -3, 2); // Solve the quadratic equation x^2 - 3x + 2 = 0 186 | ``` 187 | 188 | ### Parser 189 | 190 | ```javascript 191 | const { Parser } = require('adv-math'); 192 | 193 | const expression = '2 + 3 * (4 - 1)'; 194 | const result = Parser.parseExpression(expression); // Parse and evaluate the expression 195 | ``` 196 | 197 | ### Random 198 | 199 | ```javascript 200 | const { Random } = require('adv-math'); 201 | 202 | const randomInteger = Random.randomInt(1, 10); // Generate a random integer between 1 and 10 203 | const randomFloat = Random.randomFloat(0, 1); // Generate a random floating-point number between 0 and 1 204 | ``` 205 | 206 | ### Expression Evaluator 207 | 208 | ```javascript 209 | const { ExpressionEvaluator } = require('adv-math'); 210 | 211 | const expression = '2 + 3 * (4 - 1)'; 212 | const result = ExpressionEvaluator.evaluateExpression(expression); // Evaluate the mathematical expression 213 | console.log('Result:', result); // Output: 11 214 | ``` 215 | ## License 216 | 217 | This project is licensed under the [MIT License](LICENSE). 218 | 219 | 220 | ## Code of Conduct 221 | 222 | Please read our [Code of Conduct](CODE_OF_CONDUCT.md) to understand the standards and expectations for participating in this community. 223 | 224 | 225 | ## Contributing 226 | 227 | We welcome contributions! Please check our [Contributing Guidelines](CONTRIBUTING.md) for details on how to contribute to this project. 228 | 229 | 230 | ## Learn More 231 | 232 | For detailed documentation and usage examples, visit our [documentation](docs/). 233 | 234 | 235 | ## Developer Details 236 | 237 | - **Author:** [Pabitra Banerjee](https://pabitrabanerjee.me) 238 | - **Email:** [Pabitra Banerjee](mailto:rockstarpabitra2204@gmail.com) 239 | - **GitHub:** [PB2204](https://github.com/PB2204) 240 | 241 | 242 | ## Happy Coding 🚀 243 | 244 | We hope you find `adv-math` useful for your mathematical projects and applications. Happy coding! 245 | --------------------------------------------------------------------------------