Solving a cubic equation

后端 未结 5 1451
后悔当初
后悔当初 2020-12-16 03:24

As part of a program I\'m writing, I need to solve a cubic equation exactly (rather than using a numerical root finder):

a*x**3 + b*x**2 + c*x + d = 0.
         


        
5条回答
  •  旧巷少年郎
    2020-12-16 04:22

    Here's A. Rex's solution in JavaScript:

    a =  1.0;
    b =  0.0;
    c =  0.2 - 1.0;
    d = -0.7 * 0.2;
    
    q = (3*a*c - Math.pow(b, 2)) / (9 * Math.pow(a, 2));
    r = (9*a*b*c - 27*Math.pow(a, 2)*d - 2*Math.pow(b, 3)) / (54*Math.pow(a, 3));
    console.log("q = "+q);
    console.log("r = "+r);
    
    delta = Math.pow(q, 3) + Math.pow(r, 2);
    console.log("delta = "+delta);
    
    // here delta is less than zero so we use the second set of equations from the article:
    rho = Math.pow((-Math.pow(q, 3)), 0.5);
    theta = Math.acos(r/rho);
    
    // For x1 the imaginary part is unimportant since it cancels out
    s_real = Math.pow(rho, (1./3.)) * Math.cos( theta/3);
    t_real = Math.pow(rho, (1./3.)) * Math.cos(-theta/3);
    
    console.log("s [real] = "+s_real);
    console.log("t [real] = "+t_real);
    
    x1 = s_real + t_real - b / (3. * a);
    
    console.log("x1 = "+x1);
    console.log("should be zero: "+(a*Math.pow(x1, 3)+b*Math.pow(x1, 2)+c*x1+d));
    

提交回复
热议问题