I am new to coding! If you find this question silly then I beg your pardon at the beginning! I was trying to solve Bisection Method using java. And I successfully did it! I took user input for initial guess 'a' and 'b'! In my code I created a method that stores the "f(x) = x^3 - x - 1" and when I call this method it solves the bisection method as per my given instructions.
- The problem is I want to take the f(x) from user and use it like a formula.
- I tried to take f(x) as String once but then what next? How can I form it into a formula?
- Another problem is I cannot use '^' sign as power, I am currently using Math.pow(x,pow); Is there any way to make it('^') work as power?
- If user gives input "3x^2 - 2x - 6", how am I supposed to make the program realize that the given equation indicates (assuming x = 4) "3*4^2 - 2*4 - 6", Not "34^2 - 24 - 6" !
I went through many answers but they couldn't satisfy me! I am adding my program below, if anyone can check kindly!
//Bisection Method
package numericalMethods;
import java.util.*;
public class BisectionMethod {
public static void main(String[] args) {
double a, b, c;
Scanner sc = new Scanner(System.in);
System.out.print("Enter value of a : ");
a = sc.nextDouble();
System.out.print("Enter value of b : ");
b = sc.nextDouble();
System.out.print("Enter maximum iteration : ");
c = sc.nextDouble();
System.out.println();
if ((f(a) < 0 && f(b) > 0) || (f(a) > 0 && f(b) < 0)) {
for(int i = 1; i <= c; i++){
System.out.println("*** For iteration " + i + " ***");
System.out.println("a is a = " + a + " and b is b = " + b);
System.out.println("So f(a) is f(a) = " + f(a) + " and " + "f(b) is f(b) = " + f(b));
//declaration and calculation of root variable
double x = (a+b)/2;
System.out.println("For iteration " + i + " root is x = " + x);
System.out.println("And f(x) is f(x) = " + f(x));
System.out.println("Here f(a)*f(x) = " + (f(a) * f(x)) );
//Condition for assignment of the value of root x!
if(f(a)*f(x) < 0){
b = x;
System.out.println("As f(a)*f(x) < 0, we assign value of x to b.");
System.out.println("So now a and b are respectively, a = "+ a + " and b = " + b);
System.out.println();
}else if (f(a)*f(x) >0) {
a = x;
System.out.println("As f(a)*f(x) > 0, we assign value of x to a.");
System.out.println("Now a and b are respectively, a = "+ a + " and b = " + b);
System.out.println();
}
}
}else {
System.out.println("The condition was not fullfilled!");
}
}
//declares function
public static double f(double x){
return ((x*x*x)-x-4);
}
}