Math.js is an extensive math library for JavaScript and Node.js.

Math.js comes with a function math.evaluate to evaluate expressions.

In this blog post, we are going to see the Math.js evaluator in action with interactive code snippets powered by the Klipse plugin.

Math

Simple expressions

Easy power:

math.evaluate('sqrt(3^2 + 4^2)'); 

Implicit multiplication:

math.evaluate('(2+3)(4+5)');  

Complex numbers:

math.evaluate('sqrt(-1)').toString();
math.evaluate('sqrt(1+i)').toString();  

Easy trigonometry:

math.evaluate('cos(pi)')

But the real power of Math.js comes with the ability to define symbolic expressions…

Defining symbolic functions

First, we need to create a scope for our evaluation environment: The scope is a regular JavaScript Object that is used to resolve symbols, and to write assigned variables or function.

scope = {}

Then, we can create functions:

math.evaluate('bar(x,y) = (x+y)(x-y)', scope)

And call them:

math.evaluate('bar(10,5)', scope)

Now, let’s check that for any angle, sinus squared + cosinus squared equals 1:

math.evaluate('amp(x,y) = sqrt(x^2 + y^2)', scope)
math.evaluate('foo(x)=amp(sin(x), cos(x))', scope)
math.evaluate('foo(pi/2)',scope)

I hope that I have been able to trigger your curiousity about Math.js.

And that you cannot wait to use the Klipse plugin on your next blog post.

Happy interactive coding!