public class SqrtDemo { public static void main(String[] args){ System.out.println("Sqrt via bisection"); System.out.println(ourSqrt1(75,8,9)); System.out.println("Sqrt via Newton's method"); System.out.println(ourSqrt2(75,8)); System.out.println("Derivative of sin via differences"); System.out.println(getSinDeriv(1)); System.out.println("12345678901234567890123456789012"); System.out.println(Integer.toBinaryString(Float.floatToIntBits(2.0F))); } // use a bisection method to find as accurately possible sqrt(x) // given initial lower and upper bounds public static float ourSqrt1(float x, float lower, float upper){ if(lower*lower > x){ throw new IllegalArgumentException("lower is too large"); } else if (upper*upper < x){ throw new IllegalArgumentException("upper is too small"); } float mid = 0; while(true){ mid = (lower + upper)/2; System.out.println("lower: " + lower); System.out.println("mid " + mid); System.out.println("upper: " + upper + "\n"); // quit if cannot make any further improvement // because lower and upper are consecutive floats if(mid == lower|mid == upper){ break; } float midsq = mid*mid; if(midsq < x){ //search to right lower = mid; } else if(midsq > x){//search to left upper = mid; } } return mid; } // this method converges much faster // since we can very accurate answer very fast, // we use double instead of float // init is the initial estimate public static double ourSqrt2(double x, double init){ double s = init; double snew = 0; while(true){ // think of s and xos as being two sides of a // rectangle whose area is s*xos = x // we want the rectangle to be "more square" // so we set the new x to their average double xos = x/s; System.out.println(s); snew = (s + xos)/2; if(snew == s){ break; } s = snew; } return s; } // this illustrates cancellation public static double getSinDeriv(double x){ // suppose we have Math.sin but not cos double h = 1; double divDif = 0; for(int j=0;j<20;j++){ h = h/10; double d1 = Math.sin(x + h); double d2 = Math.sin(x); divDif = (d1 - d2)/h; System.out.println("h = " + h + "\n" + d1 + "\n"+ d2 + "\n" + divDif); } System.out.println("right answer is\n"+ Math.cos(x)); return divDif; } }