Solving Simultaneous Equations Order 3
Jun 13, 2008
I want to write javascript code to solve simultaneous equations order 3, just for fun. The challenge is to write the smallest code as possible.
For the simultaneous equations,

We can obtain the expression for x, y, z with elimination. Resulting:

Where
is the determinant defined below:

And this the smallest code I can write. Any smaller code?
<script type="text/javascript"> /* parameter m is the simultaneous equations in 3x4 matrix */ function SimEquOrd3(m) { var d = [0, 0, 0, 0]; for(var i = 0 ; i <= 3 ; i++) { var lc = (i == 0) ? 1 : 0; var mc = (i <= 1) ? 2 : 1; var rc = (i == 3) ? 2 : 3; d[i] = m[0][lc] * ( m[1][mc] * m[2][rc] - m[1][rc] * m[2][mc] ) - m[0][mc] * ( m[1][lc] * m[2][rc] - m[1][rc] * m[2][lc] ) + m[0][rc] * ( m[1][lc] * m[2][mc] - m[1][mc] * m[2][lc] ); } var x = -d[0]/d[3]; var y = d[1]/d[3]; var z = -d[2]/d[3]; return( Array(x, y, z) ); } /* always test */ var m = [ [2, -2, -1, -3], /* 2x - 2y - z - 3 = 0 */ [4, 5, -2, 3], /* 4x + 5y - 2z + 3 = 0 */ [3, 4, -3, 7] ]; /* 3x + 4y - 3z + 7 = 0 */ res = SimEquOrd3(m); alert("x="+res[0]+",y="+res[1]+",z="+res[2]); /* x=2,y=-1,z=3 */ </script>
Try it out!
| Equation 1: | |
|
| Equation 2: | |
|
| Equation 3: | |
|
Share:
Save to del.icio.us
Digg this!

Add your comment