因此,我正在尝试编写一个js函数,该函数需要3个输入(多项式,猜测和限制),并使它们返回多项式的近似根。问题是,即使限制为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

最佳答案

如注释中所指出的,所提供的代码按预期工作,问题在于检查解决方案x^2是否用于正方形x*x

但是,在大多数类似C或Java的语言中,x^y是按位“异或”(XOR),而不是幂运算。 x^y作为电源操作的符号通常在Computer Algebra Systems中找到。脚本语言(例如python或gnuplot)倾向于使用x**y

09-25 16:29
查看更多