Symbolic Computation in Javascript with Math.js

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

Math.js comes with a function math.eval 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.


Simple expressions

Easy power:

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

Implicit multiplication:


Complex numbers:


Easy trigonometry:


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.eval('bar(x,y) = (x+y)(x-y)', scope)  

And call them:

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

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

math.eval('amp(x,y) = sqrt(x^2 + y^2)', scope)  
math.eval('foo(x)=amp(sin(x), cos(x))', 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!

comments powered by Disqus