我正在尝试实现二分法来查找方程的解。
方程的形式如下:
pe^(-x) + qsin(x) + rcos(x) + stan(x) + tx^2 + u = 0 ,其中 0 ≤ p,r ≤ 20, -20 ≤ q,s,t ≤ 0 e -20 ≤ u ≤ 20
输入示例:
3
1. 0 0 0 0 -2 1
1 0 0 0 -1 2
1 -1 1 -1 -1 1
应该给出:
0.7071
不可能
0.7554
我尝试实现这个,但无法显示小数点后 4 位的结果,并且我意识到 a b 和 c 的形式是 x.x,只有一位小数。我认为问题从这里开始。任何帮助将不胜感激。这是我的代码
class p07{
public static void main(String [] args){
Scanner in = new Scanner(System.in);
int n= in.nextInt();
for (int i=0 ; i < n; i++)
bss(in.nextInt(), in.nextInt(),in.nextInt(), in.nextInt(),in.nextInt(), in.nextInt());
}
public static void bss(int p, int q, int r, int s, int t, int u){
double fa=0, fb=0, fc=0;
boolean flag=true;
double a=-20;
double b=a;
while(flag){
fa=p*Math.exp(a) + q*Math.sin(a) + r*Math.cos(a) + s*Math.tan(a) + t*Math.pow(a,2) + u;
fb=p*Math.exp(b+1) + q*Math.sin(b+1) + r*Math.cos(b+1) + s*Math.tan(b+1) + t*Math.pow(b+1,2) + u;
a++;b++;
if( (fa < 0 && fb > 0) || (fa > 0 && fb < 0) )
flag=false;
}
System.out.println("a= "+a+", b= "+b);
System.out.println("f(a)= "+fa+", f(b)= "+fb);
int k=4;
double c=0.000;
while(k!=0){
c = (a+b)/2;
fa = p*Math.exp(a) + q*Math.sin(a) + r*Math.cos(a) + s*Math.tan(a) + t*Math.pow(a,2) + u;
fc = p*Math.exp(c) + q*Math.sin(c) + r*Math.cos(c) + s*Math.tan(c) + t*Math.pow(c,2) + u;
if( fa < fc)
b=c;
else
a=c;
k--;
System.out.println("a= "+a+",b= "+b+", c= "+c);
}
double sol =p*Math.exp(c) + q*Math.sin(c) + r*Math.cos(c) + s*Math.tan(c) + t*Math.pow(c,2) + u;
System.out.println(sol);
}
}
最佳答案
一些错误:
第三个不收敛。
- 糟糕的测试:您应该测试 fa 和 fc 是否有不同的符号=> if (fa*fc<0)
- 您还应该测试是否获得 root 权限
- 我通过中断简化了您的第一个测试
- sol 不是解,而是 f(pseudo-root)
我不明白你关于小数的问题:a、b、c 是 double 的。
我将循环替换为 10 次迭代。
所以,它给出:
double fa=0, fb=0, fc=0;
double a=-20;
double b=a+1;
while(true)
{
fa=p*Math.exp(a) + q*Math.sin(a) + r*Math.cos(a) + s*Math.tan(a) + t*Math.pow(a,2) + u;
fb=p*Math.exp(b) + q*Math.sin(b) + r*Math.cos(b) + s*Math.tan(b) + t*Math.pow(b,2) + u;
if( (fa < 0 && fb > 0) || (fa > 0 && fb < 0) )
break;
a++;b++;
}
System.out.println("a= "+a+", b= "+b);
System.out.println("f(a)= "+fa+", f(b)= "+fb);
int k=10;
double c=0.0;
while(k!=0)
{
c = (a+b)/2;
fa = p*Math.exp(a) + q*Math.sin(a) + r*Math.cos(a) + s*Math.tan(a) + t*Math.pow(a,2) + u;
fc = p*Math.exp(c) + q*Math.sin(c) + r*Math.cos(c) + s*Math.tan(c) + t*Math.pow(c,2) + u;
// ROOT
if (fc==0) break;
if (fa*fc<0)
b=c;
else
a=c;
k--;
System.out.println("a= "+a+",b= "+b+", c= "+c+" f(c)"+fc);
}
double sol =p*Math.exp(c) + q*Math.sin(c) + r*Math.cos(c) + s*Math.tan(c) + t*Math.pow(c,2) + u;
System.out.println("root="+c);
关于java - 如何根据二分法求方程组的解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34476226/