/**
 * Explore the concept and possibilities of methods that return values.
 *
 * @author	Terry Sergeant
 * @version In Class Exercise
 *
*/

import java.util.Scanner;

public class FuncDemo6
{
	public static void main(String [] args)
	{
		Scanner kb= new Scanner(System.in);
		double ans,a,b,c;

		a= 1.0;
		b= 6.0;
		c= 2.0;
		
		ans= Math.sqrt(2.0);	 // we can pass a constant as a parameter and this method returns an answer
													 // we can store the answer it returns in the
													 // variable ans ... or ...
		System.out.println("The sqrt of 2 is: "+ans);
		System.out.println("The sqrt of 2 is: "+Math.sqrt(2.0));		// we can print it directly

		System.out.println("The sqrt of -2 is: "+Math.sqrt(-2.0));	// what if we give it something bogus?
		

		System.out.println("a: "+a+", b: "+b+", c: "+c);
		System.out.println("The sqrt of b is: "+Math.sqrt(b));		// we can pass a variable as a parameter
																															// as well!
		System.out.println("The sqrt of b^2 is: "+Math.pow(b,2.0));
		// NOTE: The Math.pow method accepts two (double) parameters (x,y) and returns
		// the value of x raised to the y power

		System.out.println("The sqrt of b^2-4ac is: "+Math.sqrt(Math.pow(b,2.0)-4*a*c));
									 // we can also pass a complicated mathematical
									 // expression as a parameter ... as long as the
									 // expression results in a double.	NOTE: This
									 // expression contains another method call.
		


		// OKAY.	Suppose there was no Math.sqrt method.	If we wanted to write
		// a program like this then we would need to write our own method to do
		// these calculations.
		//
		// The method we write should accept a double value as a parameter and
		// should return a double which is an approximation of a the square
		// root of its argument .... see below.
		//
		// NOW.	Redo all of the above calculations except use the method we
		// wrote.

	}


	/**
	 * Uses an iterative method to estimate sqrt.
	*/
	public static double mysqrt(double x)
	{
		double guess,result,upper,lower;

		if (x < 0.0)
			return Double.NaN;
		if (x < 1.0) {
			upper= 1;
			lower= x;
		} 
		else {
			upper= x;
			lower= 0.0;
		}
		guess= (upper+lower) / 2.0;
		result= guess*guess;

		while (Math.abs(x-result) > 0.00000000000001)
		{
			if (result > x)
				upper= guess;
			else if (result < x)
				lower= guess;
			guess= (upper+lower) / 2.0;
			result= guess*guess;
		}
		return guess;
	}
}
