Math Solving Linear Equation

[Total: 0    Average: 0/5]

Use javascript to solve linear equations.

Head Code:

<script>
function reduce(_e)
{
  var _t=_e;/* do this incase there is no math operator - just return the number */
  var _order=new Array("+","-","*","/");
  var _doOnce=true; /* only do one reduction per invocation */
  for(var i=0;i<_order.length;i++)
  {
    if(_doOnce && _e.indexOf(_order[i])!=-1)
    {
      _doOnce=false; /* don't do again */
      var _x=_e.split(_order[i]);
      switch (_order[i])
      {
        case "+": _t=parseInt(reduce(_x[0]))+parseInt(reduce(_x[1]));break;
        case "-": _t=parseInt(reduce(_x[0]))-parseInt(reduce(_x[1]));break;
        case "*": _t=reduce(_x[0])*reduce(_x[1]);break;
        case "/": _t=reduce(_x[0])/reduce(_x[1]);break;
        default : _t="-ERROR-";
      }
      for(var j=2;j<(_x.length);j++)
        switch (_order[i])
        {
          case "+": _t=parseInt(_t)+parseInt(reduce(_x[j]));break;
          case "-": _t=parseInt(_t)-parseInt(reduce(_x[j]));break;
          case "*": _t=_t*reduce(_x[j]);break;
          case "/": _t=_t/reduce(_x[j]);break;
          default : _t="-ERROR-";
        }
    }
  }
  return _t;
}
function solve()
{
  var _f=document.f1; /* form object */
  var _e=_f.e.value;  /* form.e object value */
  var _l=_e.split("=")[0]; /* left side of equation */
  var _r=_e.split("=")[1]; /* right side of equation */
  /* make 'x' be on left side */
  if(_r.indexOf("x")!=-1)
  {
    var _t; /* temp. variable used to swap values left,right */
    /* put the variable x on the left */
    _t=_l;
    _l=_r;
    _r=_t;
  }

  _r=reduce(_r); /* reduce right side */

  var _signs=new Array("+","-","*","/");
  var _signO=new Array("-","+","/","*"); /* opposite action */
  /* do each math reduction in order */
  for(var j=0;j<_signs.length;j++)
  {
    if(_l.indexOf(_signs[j])!=-1)
    {
      var _array=_l.split(_signs[j]);
      var _newL="";
      for(var i=0;i<_array.length;i++)
      {
        if(_array[i].indexOf("x")==-1)
        {
          /* we found something to subtract the reduced part from the other side */
          _r+=_signO[j]+_array[i];
          _r=reduce(_r);
        }
        else
        {
          _newL+=_array[i];
        }
      }
      _l=_newL;
    }
  }
  _f.x.value=_r;
}
</script>

Body Code:

<form name=f1>
Equation:<input name=e value="3*x+2*3=12+3*2"><BR>
<input type=button value="solve for x" onclick=solve()><BR>
<hr>
<input name=x>
</form>

Times Viewed: 25

Leave a Reply

Your email address will not be published. Required fields are marked *