Newton-Raphson解算器在Javascript中单变量方程组中的使用

时间:2019-03-13 19:16:02

标签: javascript arrays for-loop do-while newtons-method

我想对一维数组A,B和C中定义的参数a,b和c的各种值分别求解ax ^ 2- -bx + c形式的方程。

const A = [1, 1, 1]
const B = [5, 3, 2];
const C = [4, 2, 1];
var i = 0
var x0 = [10, 12, 11];
var x1 = [];
var fx = [];
var fxp = [];
const tol = [0.1, 0.1, 0.1]
for (let j = 0; j < A.length; j++) {
    do {
        x1[j] = x0[j];
        fx[j] = A[j] * x1[j] * x1[j] - B[j] * x1[j] + C[j]; //function 
        fxp[j] = 2 * A[j] * x1[j] - B[j]; //first derivative of f(x)
        x0[j] = x1[j] - fx[j] / fxp[j];
        i++
        if (i > 100) break;
    } while (x0[j] - x1[j] < tol[j])
}

console.log("x1", x1)

我将do-while循环迭代器放置在for循环中,但我的担忧/问题是:

  1. 仅第一个方程求解(即A [0],B [0],C [0]),其他两个方程只返回x1的初始猜测。
  2. 是否有更好的方法来实现我的目标,因为当A.length >>>很大时,在for循环中循环迭代器可能会在计算上变得昂贵?

1 个答案:

答案 0 :(得分:0)

该代码是为二次方程式而设计的,但是只要您得到方程的一阶导数,就可以轻松地将其应用于其他方程。 “ fx”是函数,而“ fxp”是一阶导数。

如本例所示,

Newton-Raphson对初始化非常敏感。对于具有两个根的二次函数,您将得到两个不同的值,具体取决于初始值...因此请仔细选择初始值。

//CASE ONE
const A = [1, 1, 1]
const B = [5, 3, 2];
const C = [4, 2, 1];
var x0 = [14, 13, 11];
var x1 = [14, 13, 11];
var fx = [];
var fxp = [];
const tol = [0.000001, 0.000001, 0.000001]
const error = [];
for (i = 0; i < 1000; i++) {
    for (let j = 0; j < A.length; j++) {
        x1[j] = x0[j];
        fx[j] = A[j] * x1[j] * x1[j] - B[j] * x1[j] + C[j]; //function 
        fxp[j] = 2 * A[j] * x1[j] - B[j]; //first derivative of f(x)
        x0[j] = x1[j] - fx[j] / fxp[j];
        error[j] = Math.abs(x1[j] - x0[j]);
        if (error[j] < tol[j]) {
            break;
        }
    }
}

console.log("x1", x1, "error", error)

//CASE TWO
const A = [1, 1, 1]
const B = [5, 3, 2];
const C = [4, 2, 1];
var x0 = [0, 0, 0];
var x1 = [0, 0, 0];
var fx = [];
var fxp = [];
const tol = [0.000001, 0.000001, 0.000001]
const error = [];
for (i = 0; i < 1000; i++) {
    for (let j = 0; j < A.length; j++) {
        x1[j] = x0[j];
        fx[j] = A[j] * x1[j] * x1[j] - B[j] * x1[j] + C[j]; //function 
        fxp[j] = 2 * A[j] * x1[j] - B[j]; //first derivative of f(x)
        x0[j] = x1[j] - fx[j] / fxp[j];
        error[j] = Math.abs(x1[j] - x0[j]);
        if (error[j] < tol[j]) {
            break;
        }
    }
}

console.log("x1", x1, "error", error)