16

Symbolic Computation in JavaScript with Math.js

 3 years ago
source link: https://blog.klipse.tech/javascript/2020/09/10/symbolic-computation-math-js.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Symbolic Computation in JavaScript with Math.js

Sep 10, 2020 • Yehonathan Sharvit

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

  Object.keys(math)

Simple expressions

Easy power:

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

Implicit multiplication:

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

Complex numbers:

xxxxxxxxxx
math.evaluate('sqrt(-1)').toString();
xxxxxxxxxx
"i"
xxxxxxxxxx
math.evaluate('sqrt(1+i)').toString();  
xxxxxxxxxx
"1.09868411346781 + 0.45508986056222733i"

Easy trigonometry:

xxxxxxxxxx
math.evaluate('cos(pi)')
xxxxxxxxxx
-1

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.

xxxxxxxxxx
scope = {}
xxxxxxxxxx
Object {}

Then, we can create functions:

xxxxxxxxxx
math.evaluate('bar(x,y) = (x+y)(x-y)', scope)
xxxxxxxxxx
[Function bar]

And call them:

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

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

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

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!

If you enjoy this kind of interactive articles would you consider a (small) donation💸 on Patreon or at least giving a star⭐ for the Klispe repo on Github?

to stay up-to-date with the coolest interactive articles around the world.

Discover more cool interactive articles about javascript, clojure[script], python, ruby, scheme, c++ and even brainfuck!

Give Klipse a Github star to express how much you appreciate Code Interactivity.

Subscribe to the Klipse newsletter:

Feel free to email me [email protected] for getting practical tips and tricks in writing your first interactive blog post.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK