I have to write a program which finds an approximate solution to an equation f(x)=0 for some function f using the bisection method. To solve the program using the method first find two values of x, A,and B, such that when evaluated in the function f(x) they give opposite signs for the y value. Treat the positive value as an upper bound and the negative value as a lower bound. Divide the space between A and B in half and evaluate the function at that new point. I'm supposed to test my program using multiple polynomials. Use at least 3 methods. One to read 5 coefficients, one to calculate the value of the polynomial, and one to do the binary bisection search.
public class Bisection2 { public static void main(String args[]) { } private double precision = .000001; private double cubic(double x) { double Fn = ((Math.pow(x,3)) - (7 * (Math.pow(x,2))) + (5 * x) + 3); return (Fn); } private double bisector(double left, double right) { double midpoint; while (Math.abs(right - left) > precision) { // Find the Midpoint of the funtion midpoint = ((left + right) / 2); System.out.print(midpoint); System.out.print("\n"); //determine the appropriate half to search in if ((cubic(left) * cubic(midpoint)) > 0) left = midpoint; else right = midpoint; } return ((left + right) / 2); } private int Main() { System.out.print(bisector(0, 2)); System.out.print("\n"); System.out.print(bisector(5, 7)); System.out.print("\n"); return 0; } }public class BisectionMethod { public static void main(String argv[]) { double x = 0, del = 1e-6, a = 1, b = 2; double dx = b-a; int k = 0; while (Math.abs(dx) > del) { x = (a+b)/2; if ((f(a)*f(x)) < 0) { b = x; dx = b-a; } else { a = x; dx = b-a; } k++; } System.out.println("Iteration number: " + k); System.out.println("Root obtained: " + x); System.out.println("Estimated error: " + dx); } // Method to provide function f(x)=exp(x)*log(x)-x*x. public static double f(double x) { return Math.exp(x)*Math.log(x)-x*x; } }
Here are two programs I have created, but I don't think they are exactly what the assignment is asking for. I think I have to use the system console to ask for the coefficients of x^whatever power. and if the x raised to that power does not exist enter in a zero for the coefficient. I'm not exactly sure how I would do this and the first program I created isn't running either. I just started programming and have been stuck on this one for a while now. Any help would be greatly appreciated. Creating the methods is what I struggle the most with.