Mathematics in javascript


jMath extends javascripts basic math library with the notion of Vectors and Matrices and adds visualization by 2d plots and histograms.

Both jVector and jMatrix are able to do other things as well, try them out here:
GitHub

Download jVector
Download jMatrix
Download jPlot2D
Note that jPlot2D requires Raphaël JS

Basic functions of jVector:


// Create two vectors
var vec1 = new Vector(1.0, 1.0, 2.0);
var vec2 = new Vector(4.0, 2.3, 5.0);

// Calculate the dot product of the vectors
var scalar1 = vec1.Dot(vec2);
console.log(scalar1); // –>16.3

// Scale vec1 by scalar1
vec1 = vec1.Scale(scalar1);
console.log(vec1); // –> x: 16.3, y:16.3, z:32.6

// Cross product of vec2 and vec1
vec3 = vec2.Cross(vec1);
console.log(vec3); // –> x: -6.519 y: -48.90 z: 27.71

// Get the L2 norm of vec3:
scalar2 = vec3.Norm();
console.log(scalar2); // –> 56.582

// Return vec3 in Spherical coordinates:
sph3 = vec3.Spherical();
console.log(sph3); // –> phi: -1.70, r: 56.58, theta: 1.059

// Calculate ((vec1 + vec2) * vec3) * scalar1
vec4 = vec1.Add(vec2).Mult(vec3).Scale(scalar1);
console.log(vec4); // –> x: -2157.40, y: -14825.50, z: 16982.90
Part of the Orbital Simulator uses jVector when solving the differential equations in 3 dimensions:
// Calculates the next position in the orbit
function nextPosition(r,v,dt){
    var r_i = r.Add(v.Scale(dt)); // r + v*dt
    var rr = r.Add(r_i); // r+r_i
    var r_scalar = Math.sqrt( rr.Dot(rr) / 4.0);
    var v_i = v.Sub( r.Add(r_i).Scale(MU*Math.pow(r_scalar,-3.0) * dt / 2.0)); // v - MU*Math.pow(r_scalar,-3.0) * (r+r_i) * dt / 2.0
    r_i = r.Add( v.Add(v_i).Scale(dt / 2.0));
    return {"r_i" : r_i, "v_i" : v_i};
};

jMatrix

The matrix package handles matrices, and the basic mathematics behind. The Atmospheric Reentry Simulator works on a massive set of differential equations, solving 7 equations at once, the core solver basically multiplies a 7x7 matrix with a 7-vector and adds a tiny part of it to the new updated state of variables.
		var A = new Matrix([
			[-Br * Math.tan(X.mat[4][0]),0,0,0,0,0,0],
			[-2.0*X.mat[1][0]*Math.sqrt(Br)/Math.cos(X.mat[4][0])*(1.0+lift_to_drag*Math.cos(sigma)*Math.tan(X.mat[4][0])),0,0,0,0,0,0],
			[0,0,0,0,0,0,0],
			[0,0,0,0,0,0,0],
			[Math.sqrt(Br)/Math.cos(X.mat[4][0])*lift_to_drag*Math.cos(sigma),0,0,0,0,0,0],
			[Math.sqrt(Br)/Math.pow(Math.sin(X.mat[4][0]),2)*lift_to_drag*Math.sin(sigma),0,0,0,0,0,0],
			[0,0,0,0,0,0,0]
			]);

		var B = new Matrix([
			[0],
			[-X.mat[1][0]*Math.sin(X.mat[4][0])/Math.cos(X.mat[4][0])],
			[Math.cos(X.mat[5][0])/Math.cos(X.mat[3][0])],
			[Math.sin(X.mat[5][0])],
			[(1.0 - Math.pow(Math.cos(X.mat[4][0]),2)/X.mat[1][0])],
			[-Math.cos(X.mat[5][0])*Math.tan(X.mat[3][0])],
			[r * Math.sqrt(r) /Math.sqrt(X.mat[1][0]*mu) ] 
			]);

		var xo = A.Mult(X).Add(B);
		this.X = X.Add(xo.Scale(s[0]));