Star

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.

Math

Simple expressions

Easy power:

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

Implicit multiplication:

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

Complex numbers:

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

Easy trigonometry:

math.eval('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.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)  
math.eval('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!

comments powered by Disqus