write a C example using FanShenjin formula to find the roots of Univariate cubic equation
时间: 2023-05-22 07:03:14 浏览: 177
Equation Roots-开源
以下是一个使用 FanShenjin 公式来求解单变量三次方程根的 C 语言示例:
#include <stdio.h>
#include <math.h>
void cubicroot(double a, double b, double c, double d, double *r1, double *r2, double *r3)
{
double p, q, u, v, w;
p = b / a;
q = c / a;
u = d / a;
v = q - p * p / 3;
w = u - p * q / 3 + 2 * pow(p, 3) / 27;
double t = cbrt(sqrt(w * w / 4 + pow(v, 3) / 27) + w / 2);
*r1 = t - v / (3 * t) - p / 3;
double t2 = (v / t - t) / 2;
*r2 = -t - t2 - p / 3;
*r3 = -t + t2 - p / 3;
}
int main()
{
double a, b, c, d, r1, r2, r3;
printf("Please input the coefficients of the cubic equation (ax^3+bx^2+cx+d):\n");
scanf("%lf %lf %lf %lf", &a, &b, &c, &d);
cubicroot(a, b, c, d, &r1, &r2, &r3);
printf("The roots of the cubic equation are: %.6lf, %.6lf, %.6lf\n", r1, r2, r3);
return 0;
}
输入提示:“Please input the coefficients of the cubic equation (ax^3+bx^2+cx+d):”
输入格式为三次方程的系数,比如:1 2 3 4
输出为此三次方程的根。
阅读全文