Newtons Method In JS Being Inaccurate

373 views Asked by At

So, I am trying to write a js function that takes 3 inputs (polynomial, guess and limit) and make them return the approximate root of the polynomial. The problem is that, even with a limit of 1000, the result is still very inaccurate. Does anybody have any ideas on why this may be?

The Method

The code:

var derivativeOfATerm = function(arr) {
  var one = arr[0];
  var two = arr[1];
  var derivative = [];
  if (two <= 0) {
    return [0, 0];
  } else {
    derivative.push(one * two);
    derivative.push(two - 1);
    return derivative;
  }
};

var derivativeOfPolynomial = function(arr, order = 1) {
  var derivative = [];
  for (var i = 0; i < arr.length; i++) {
    //console.log(arr[i]);
    derivative.push(derivativeOfATerm(arr[i]));
  }
  if (order === 1) {
    return derivative;
  } else {
    return derivativeOfPolynomial(derivative, order - 1);
  }
};

var runPolynomial = function(poly, num) {
  var array = [];
  for (var i = 0; i < poly.length; i++) {
    array.push(Math.pow(num, poly[i][1]) * poly[i][0]);
  }
  return array.reduce((a, b) => a + b);
};

var newtonRootFind = function(polynomial, guess, limit = 10) {
  var derivative = derivativeOfPolynomial(polynomial);
  var previous = guess;
  var next;
  for (var i = 0; i < limit; i++) {
    next = previous - (runPolynomial(polynomial, previous)) / (runPolynomial(derivative, previous));
    previous = next;
    console.log("%o : x=%o, p(x)=%o", i+1, next, runPolynomial(polynomial, next));
  }
  return previous;
};

console.log("result x=",newtonRootFind([[1,2],[1,1],[-5,0]], 5, 10));

I'm only 12 so try not to use that many technical terms. For example, entering [[1,2],[1,1],[-5,0]] or x^2+x-5, it returns 1.79128784747792, which isn't accurate enough. It equals 4.79... when it should be very close to 5.

1

There are 1 answers

0
Lutz Lehmann On

As worked out in the comments, the presented code works as intended, the problem was that in checking the solution x^2 was used for the square x*x.

However, x^y in most C- or Java-like languages is the bitwise "exclusive or", XOR, not the power operation. x^y as symbol for the power operation is usually found in Computer Algebra Systems. Script languages as python or gnuplot tend to use x**y.