JS中的牛顿法不准确

时间:2016-12-23 19:49:43

标签: javascript math numerical-methods polynomial-math

所以,我正在尝试编写一个带有3个输入(多项式,猜测和限制)的js函数,并使它们返回多项式的近似根。问题是,即使限制为1000,结果仍然非常不准确。有没有人对这可能是什么有任何想法?

The Method

代码:

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));

我只有12岁,所以尽量不要使用那么多技术术语。 例如,输入[[1,2],[1,1],[-5,0]]x^2+x-5,它会返回1.79128784747792,这不够准确。当它应该非常接近4.79...时,它等于5

1 个答案:

答案 0 :(得分:2)

正如评论中所述,所呈现的代码按预期工作,问题在于检查解决方案x*x用于方x^y

但是,大多数C语言或类Java语言中的x^y是按位“异或”,XOR,而不是幂操作。 x**y作为电源操作的符号通常可以在Computer Algebra Systems中找到。脚本语言如python或gnuplot倾向于使用<dependency> <groupId>info.cukes</groupId> <artifactId>gherkin</artifactId> <version>2.7.3</version> </dependency>