THE RISE OF JAVASCRIPT
Create and use an
object
obj = {a: 2, b:
3}
c = obj.a +
obj.b
obj = {a: 2, b: 3}
c = obj.a + obj.b
The math.js syntax is much more concise than the native JavaScript API. Math.js also uses one-
based
indices rather than zero-based, since the former is more common in mathematics software
applications. Each math.js operator has an associated function in the native JavaScript API,
which satisfies the needs of both audiences served by math.js: programmers and mathematicians.
The math.js syntax is understood by the built-in expression parser. Parsing
an expression returns
an abstract syntax tree
27,28
representing the expression:
var tree = math.parse('3x ^ 2 + 5'); // abstract syntax tree
Math.js evaluates this expression by first compiling the tree into native JavaScript code. The
compiled code can then be evaluated while providing values for any symbols used in the expres-
sion:
var compiled = tree.compile();
var result = compiled.eval( {x: 4} ); // 53
Math.js can also perform algebraic operations by transforming abstract syntax trees:
var tree = math.parse('x * x^2 ');
math.simplify(tree); // x ^ 3
math.derivative(tree); // 3 * x ^ 2
The math.js syntax and expression parser are demonstrated further in the following case study.
CASE STUDY: ROCKET TRAJECTORY
OPTIMIZATION
In this example, we show how math.js can be extended using a custom
function to solve a sys-
tem of ordinary differential equations (ODEs). We will demonstrate this by simulating the ascent
stage of the Apollo Lunar Module. In solving this problem, we will try to maintain generality so
that the same methods can be used to solve many different systems of ODEs.
For reference, the
full code of this case study can be found in the examples section of the math.js library.
29
The lunar ascent can be modeled using the following system of ODEs, representing the motion
of an object in orbit around a planet or moon:
( )
dr
v sin
dt
γ
= ⋅
( )
2
dv
T
sin
dt
r
m
μ
γ
−
=
⋅
+
0
sp
dm
T
dt
g I
−
=
( )
d
v
cos
dt
r
φ
γ
=
( )
1
d
v
cos
dt
r
r v
γ
μ
γ
=
−
⋅
24
January/February 2018
www.computer.org/cise
COMPUTING IN SCIENCE &
ENGINEERING
The quantities
r
and
φ
specify the object’s position in polar coordinates and represent, respec-
tively, the distance from the object to the center of the moon and the
angular position of the ob-
ject relative to some reference point. The quantity
Do'stlaringiz bilan baham: