I'm trying to implement the bisection method for finding the solutions of an equation.
The form of the equation is like this:
pe^(-x) + qsin(x) + rcos(x) + stan(x) + tx^2 + u = 0 , with 0 ≤ p,r ≤ 20, -20 ≤ q,s,t ≤ 0 e -20 ≤ u ≤ 20
input example:
3
1. 0 0 0 0 -2 1
1 0 0 0 -1 2
1 -1 1 -1 -1 1
should give :
0.7071
Impossible
0.7554
I tried to implement this but I can't display the result with 4 decimal places, and I realized that a b and c are in the form of x.x with only one decimal place. I think the problem starts here. Any help would be very appreciated . Here's my code
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);
}
}
some errors:
the third one doesnt converge.
I dont understand your problem about decimals: a,b,c are double.
I replace the loop with 10 iterations.
so, it gives:
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);