mathjs code example

Example 1: js maths

JS Numbers and Math:

Number Properties:
MAX_VALUE
The maximum numeric value representable in JavaScript
MIN_VALUE
Smallest positive numeric value representable in JavaScript
NaN
The “Not-a-Number” value
NEGATIVE_INFINITY
The negative Infinity value
POSITIVE_INFINITY
Positive Infinity value

Number Methods:
toExponential()
Returns a string with a rounded number written as exponential notation
toFixed()
Returns the string of a number with a specified number of decimals
toPrecision()
String of a number written with a specified length
toString()
Returns a number as a string
valueOf()
Returns a number as a number

Math Properties:
E Euler’s number
LN2 The natural logarithm of 2
LN10 Natural logarithm of 10
LOG2E Base 2 logarithm of E
LOG10E Base 10 logarithm of E
PI The number PI
SQRT1_2 Square root of 1/2
SQRT2 The square root of 2

Math Methods:
abs(x)
Returns the absolute (positive) value of x
acos(x)
The arccosine of x, in radians
asin(x)
Arcsine of x, in radians
atan(x)
The arctangent of x as a numeric value
atan2(y,x)
Arctangent of the quotient of its arguments
ceil(x)
Value of x rounded up to its nearest integer
cos(x)
The cosine of x (x is in radians)
exp(x)
Value of Ex
floor(x)
The value of x rounded down to its nearest integer
log(x)
The natural logarithm (base E) of x
max(x,y,z,...,n)
Returns the number with the highest value
min(x,y,z,...,n)
Same for the number with the lowest value
pow(x,y)
X to the power of y
random()
Returns a random number between 0 and 1
round(x)
The value of x rounded to its nearest integer
sin(x)
The sine of x (x is in radians)
sqrt(x)
Square root of x
tan(x)
The tangent of an angle

Example 2: math js

function sum(a, b) {
  return a + b;
}

function subtract(a, b) {
  return a - b;
}

function multiply(a, b) {
  return a * b;
}

function divide(a, b) {
  if (b === 0) {
    console.log("can't divide by zero");
  }

  if (a === 0 && b === 0) {
    console.log("undetermined");
  }

  //or this without any IFs
  return a / b;
}

Example 3: math.js

// functions and constants
math.round(math.e, 3)                // 2.718
math.atan2(3, -3) / math.pi          // 0.75
math.log(10000, 10)                  // 4
math.sqrt(-4)                        // 2i
math.derivative('x^2 + x', 'x')      // 2*x+1
math.pow([[-1, 2], [3, 1]], 2)
     // [[7, 0], [0, 7]]

// expressions
math.evaluate('1.2 * (2 + 4.5)')     // 7.8
math.evaluate('12.7 cm to inch')     // 5 inch
math.evaluate('sin(45 deg) ^ 2')     // 0.5
math.evaluate('9 / 3 + 2i')          // 3 + 2i
math.evaluate('det([-1, 2; 3, 1])')  // -7

// chaining
math.chain(3)
    .add(4)
    .multiply(2)
    .done() // 14