2022.02.21一元三次方程求解
题目描述
有形如:ax3+bx2+cx+d=0a x^3 + b x^2 + c x + d = 0ax3+bx2+cx+d=0 这样的一个一元三次方程。给出该方程中各项的系数(a,b,c,d 均为实数),并约定该方程存在三个不同实根(根的范围在 -100 至 100 之间),且根与根之差的绝对值 ≥1\ge 1≥1。要求由小到大依次在同一行输出这三个实根(根与根之间留有空格),并精确到小数点后 2 位。
提示:记方程 f(x) = 0,若存在 2 个数 x1x_1x1 和 x2x_2x2 ,且 x1<x2x_1 < x_2x1<x2,f(x1)×f(x2)<0f(x_1) \times f(x_2) < 0f(x1)×f(x2)<0,则在$ (x_1, x_2)$ 之间一定有一个根。
输入格式
一行,4 个实数 a,b,c,d。
输出格式
一行,3 个实根,从小到大输出,并精确到小数点后 2 位。
样例输入
1 -5 -4 20
样例输出
-2.00 2.00 5.00
思路
思路1:穷举
从-100出发,每次走0.01,并记录其函数值的绝对值大小,最接近0的三个数值,认为是解。
代码
double a,b,c,d;
Node[] ns = new Node[20000];
double f(double x) {
return a*Math.pow(x, 3)+b*Math.pow(x, 2)+c*x+d;
}
String getRes(double A, double B, double C) {
double[] ts = new double[3];
ts[0] = A;
ts[1] = B;
ts[2] = C;
Arrays.sort(ts);
return "".format("%.2f", ts[0])+" "+"".format("%.2f", ts[1])+" "+"".format("%.2f", ts[2]);
}
void test() throws IOException {
Reader cin = new Reader();
a = cin.nextDouble();
b = cin.nextDouble();
c = cin.nextDouble();
d = cin.nextDouble();
double x = -100;
int i = 0;
while(x <= 100) {
ns[i++] = new Node(x, Math.abs(f(x)));
x+=0.01;
}
Arrays.sort(ns);
System.out.println(getRes(ns[0].x,ns[1].x,ns[2].x));
}
class Node implements Comparable<Node>{
double x;
double err;
Node(double x, double err) {
this.x = x;
this.err = err;
}
public int compareTo(Node o) {
if(err<o.err) return -1;
else if(err>o.err) return 1;
return 0;
}
}
思路2:二分
上述思路并没有考虑到题目中的条件:根与根之间的差大于1,可以根据该推论,得到以下结论:
根于根之间差大于1 —> 在长度为1的区间内,只可能最多存在一个根。
而只存在一个根的条件是区间首尾的函数值相等。所以,如果一个区间首尾函数值同号,则区间内无解,否则利用二分查找求解
代码2
void test2() throws IOException {
Reader cin = new Reader();
a = cin.nextDouble();
b = cin.nextDouble();
c = cin.nextDouble();
d = cin.nextDouble();
for(int i = -100; i < 100; i++) {
// 得到区间 [i, i+1)
if(f(i) == 0) System.out.print("".format("%.2f",(double)i)+" ");
else if(f(i)*f(i+1) < 0) {
System.out.print("".format("%.2f",find(i, i+1))+" ");
}
}
}
double find(double l, double r) {
if(Math.abs(l-r) < 0.001) return l;
double mid = (l+r)/2;
if(f(mid)*f(l) <= 0) return find(l, mid);
else return find(mid, r);
}