// f(x) = x^3 + cx + d = 0 public static double[] Solve(double c, double d) { if (d < 0) { return(Solve(c, -d).Reverse().Select(x => - x).ToArray()); } // 自明解 if (d == 0 && c >= 0) { return new[] { 0D } } ; // 負の実数解 var x1 = SolveNegative(); // f(x) = (x - x_1) (x^2 + x_1 x + x_1^2 + c) return(QuadraticEquation0.Solve(1, x1, x1 * x1 + c).Prepend(x1).ToArray()); double SolveNegative() { var f = CreateFunction(c, d); var f1 = CreateDerivative(c); var x0 = -1D; while (f(x0) > 0) { x0 *= 2; } return(NewtonMethod.Solve(f, f1, x0)); } } }
// f(x) = ax^3 + bx^2 + cx + d = 0 public static double[] Solve(double a, double b, double c, double d) { if (a == 0) { throw new ArgumentException("The value must not be 0.", nameof(a)); } if (a < 0) { return(Solve(-a, -b, -c, -d)); } var f = CreateFunction(a, b, c, d); var xc = -b / (3 * a); var yc = f(xc); if (yc < 0) { return(Solve(a, -b, c, -d).Reverse().Select(x => - x).ToArray()); } var f1 = CreateDerivative(a, b, c); // 自明解 if (yc == 0 && f1(xc) >= 0) { return new[] { xc } } ; // xc より小さい実数解 var x1 = SolveNegative(); var p = a * x1 + b; var q = p * x1 + c; return(QuadraticEquation0.Solve(a, p, q).Prepend(x1).ToArray()); double SolveNegative() { var x0 = -1D; while (f(xc + x0) > 0) { x0 *= 2; } return(NewtonMethod.Solve(f, f1, xc + x0)); } } }