/* 
   Assignment #2  CS100B
   
   Calculates sheet pile depth using the Newton's method
   
   Author:		CS100B Student
   CUID:		123456
   Section:		99, Sunday, 10:00pm, CS100B TA
   
   Signature:	        My Signature
*/
   
// class Newton
//
// use the Newton's method to find the root in the sheet pile equation
// the result is saved in field "x"
public class Newton{

    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;
	
	// variable declaration
	double x;		// root of the equation
	int iterations;		// number of iterations to reach root
	
	// pick initial value and assign to x
	x = 3.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;

	// pick step size
	double increment = 0.00001;
	double f_of_x;				// value of function
	double deriv;				// value of derivative
	double delta = 100;			// ratio of the two

	// continue if tolerance not met
	while(delta > TOLERANCE) {

	    // compute f(x)
	    f_of_x = Math.pow(x,4) -
	             8*P*Math.pow(x,2)/((GAMMA*(Kp - Ka))) -
	             12*P*L*x/((GAMMA*(Kp - Ka))) -
	             Math.pow((2*P/((GAMMA*(Kp - Ka)))),2);

	    // compute f'(x)
	    deriv =  4*Math.pow(x,3) - 16*P*x/((GAMMA*(Kp - Ka))) -
	             12*P*L/((GAMMA*(Kp - Ka)));

	    // compute delta = f(x)/f'(x)
	    delta = -f_of_x/deriv;
			
	    // update x if tolerance is not met
	    x += delta;
			
	    // count number of interations
	    iterations += 1;
        }

	// display the results currently in the fields root and iterations
	System.out.println("\nThe Newton's method was used to " +
			   "solve the problem!\n");
	System.out.println("The root, " + x + " was obtained in " +
			   iterations + " iterations.\n");

    } // main method

}  // class Newton
