/* 
   Assignment #2  CS100B
   
   SheetPile.java
   --calculates sheet pile depth using the lhs/rhs, bisecton, and
     Newton's methods
   
   Author:		CS100B Student
   CUID:		123456
   Section:		99, Sunday, 10:00pm, CS100B TA
   
   Signature:	        My Signature
*/ 
   


// class Bisection
//
// use the bisection method to find the root in the sheet pile equation
// the result is saved in field "mid"
class Bisection {

    public static void main(String[] args){

	// given constants
	final double TOLERANCE = 0.001;
	final double GAMMA = 18.0;
	final double PHI = 30.0;
	final double L = 3.0;
	final double P = 30.0;
	
	// declaration of variables
	double left;		// left end point of the bisection
	double right;		// right end point of the bisection
	double mid;		// midpoint of the bisection
	int iterations;		// number of iterations to reach root
	
	// pick starting and ending points; interval must contain root
	left = 2.0;
	right = 5.0;
	mid = 0.0;
	iterations = 0;
	
	// compute values of constants (note that arguments of trig.
	// functions must be in radians)
	double Ka = Math.tan((45 - PHI/2)*Math.PI/180);
	Ka *= Ka;		// tan^2
	double Kp = Math.tan((45 + PHI/2)*Math.PI/180);
	Kp *= Kp;
	
	// initialize values of the function
	double f_left, f_right, f_mid = 100;	
	    	
	// keep repeating steps until tolerance is satisfied 
	while(Math.abs(f_mid - 0.0) > TOLERANCE) {

	    // compute mid-point of domain
	    mid = (left + right)/2.;

	    // compute value of function at left, right, and
	    // mid points
	    f_left = Math.pow(left,4) -
	      8*P*Math.pow(left,2)/((GAMMA*(Kp - Ka))) -
	      12*P*L*left/((GAMMA*(Kp - Ka))) -
	      Math.pow((2*P/((GAMMA*(Kp - Ka)))),2);

	    f_right = Math.pow(right,4) -
	      8*P*Math.pow(right,2)/((GAMMA*(Kp - Ka))) -
	      12*P*L*right/((GAMMA*(Kp - Ka))) -
	      Math.pow((2*P/((GAMMA*(Kp - Ka)))),2);

	    f_mid = Math.pow(mid,4) -
	      8*P*Math.pow(mid,2)/((GAMMA*(Kp - Ka))) -
	      12*P*L*mid/((GAMMA*(Kp - Ka))) -
	      Math.pow((2*P/((GAMMA*(Kp - Ka)))),2);

	    // Xm is to the left of root
	    if(f_mid * f_right < 0) {
	      left = mid;
	    }
	    // Xm is to the right of the root
	    else if(f_mid * f_left < 0) {
	      right = mid;
	    }
	    // f_mid = 0 or error
	    else {
	      System.err.println("Oops....");
	    }

	    iterations += 1;

        }

	// display the results currently in the fields root and iterations

		System.out.println("\nThe bisection method was used to " +
			"solve the problem!\n");
		System.out.println("The root, " + mid + " was obtained in " +
	     	iterations + " iterations.\n");

    } // method main

} // class Bisection
