package ClassWork;
import java.util.Scanner;
/**
* 【例3】一元三次方程求解
* 有形如:ax3+bx2+cx+d=0这样的一个一元三次方程。给出该方程中各项的系数(a,b,c,d均为实数),并约定该方程存在三个不同实根(根的范围在-100至100之间),且根与根之差的绝对值≥1。
* 要求由小到大依次在同一行输出这三个实根(根与根之间留有空格),并精确到小数点后2位。
* 提示:记方程f(x)=0,若存在2个数x1和x2,且x1<x2,f(x1)*f(x2)<0,则在(x1,x2)之间一定有一个根。
* 输入:a,b,c,d 输出:三个实根(根与根之间留有空格)
* 【输入输出样例】
* 输入:1 -5 -4 20 输出:-2.00 2.00 5.00
* @author Ravanla
* @create 2019-04-26-19:12
*/
public class SolvingEquations {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入a, b, c, d(ax3+bx2+cx+d=0)");
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
int d = sc.nextInt();
System.out.println("-------------枚举法-------------");
se01(a, b, c, d);
System.out.println("-------------分治法-------------");
se02(a, b, c, d);
}
// 分治法
private static void se02(int a, int b, int c, int d) {
int account = 0;
//没隔20为一个区间
for(int x = -100; x < 100; x += 1){
int x1 = x;
int x2 = x + 1;
if(f(x, a, b, c, d) == 0) System.out.println(x + " ");
else{
if(f(x1, a, b, c, d) * f(x2, a, b, c, d) < 0){
while (x2 - x1 >= 0.001) {
int mid = (x2 + x1)/2;
if(f(x1, a, b, c, d) * f(mid, a, b, c, d) <= 0) x2 = mid;
else x1 = mid;
}
System.out.println((double)x1);
}
}
// int x1 = x;
// int x2 = x + 1;
// if (f(x1, a, b, c, d) * f(x2, a, b, c, d) < 0) {
// //采用分治法
int left = x;
int right = x + 20;
// int mid;
// //二分法
// while(x1 <= x2){
// mid = (x1 + x2)/2;
// //如果中值小于0 左区间的数都小于0,让中值直接从左区间开始再算就好了
// if(f(mid, a, b, c, d) <= 0) x1 = mid + 1;
// //如果中值大于0 右区间的数都大于0,让中值直接从右区间开始再算就好了
// else x2 = mid - 1;
// }
// //找出三个根既可以结束搜索了
// if (++account == 3) {
// break;
// }
// //输出根
// System.out.print(x2 + " ");
// }
// if(f(x, a, b, c, d) == 0){
// System.out.println(x + " ");
// }
}
}
// 函数
public static double f(double x, double a, double b, double c, double d){
return x*x*x*a + b*x*x + c*x + d;
}
// 枚举法
public static void se01(double a, double b, double c, double d){
int account = 0;
for(int x = -100; x < 100; x++){
double x1 = (x - 0.05)/100;
double x2 = (x + 0.05)/100;
if(f(x1, a, b, c, d) * f(x2, a, b, c, d) < 0 || f(x, a, b, c, d) == 0){
System.out.print((double)x + " ");
//找出三个根既可以结束搜索了
if(++account == 3){
break;
}
}
}
}
}
算法--一元三次方程--Java实现
最新推荐文章于 2022-10-20 16:11:13 发布