/** * Demonstrate the while statement in Java * for problems * involving convergence, meeting/exceeding thresholds * * @author (Michael Branicky) */ public class Thresholds { // How long to a billion (starting with $currentSavings at interestRate% interest)? public static int yearsUntilRetirement (double currentSavings, double interestRate) { int years = 0; double principal = currentSavings; double multiplier = 1.0 + interestRate/100.0; while (principal < 1E9) { principal = principal * multiplier; years = years + 1; } return years; } // Pharmacokinetics of ibuprofen // REF: http://www.rxlist.com/cgi/generic/ibup_cp.htm public static double hoursUntil1mg (double dose) { // peak level is up to 80% of dose after 1-2 hours double serumAmount = 0.8*dose; double hours = 1.5; // half-life is 1.8 to 2 hrs while (serumAmount>1.0) { serumAmount = 0.5*serumAmount; hours = hours + 1.9; } return hours; } // Newton iteration for the square root function // REF: http://en.wikipedia.org/wiki/N-th_root_algorithm public static double sqrtViaNewton (double a) { double guess = 1.0; while (Math.abs(guess-a/guess)>1E-6) { guess = 0.5*(guess + a/guess); } return guess; } // same method, but takes guess and tolerance as parameters public static double sqrtViaNewton (double a, double guess, double tol) { while (Math.abs(guess-a/guess)>tol) { guess = 0.5*(guess + a/guess); } return guess; } public static void main(String args[]) { // Test/use the yearsUntilRetirement method System.out.println(yearsUntilRetirement(1E6, 10.0)+" years to a billion"); // Test/use the hoursUntil1mg method System.out.println("800mg ibuprofen to 1mg in ~"+hoursUntil1mg(800.)+" hours"); // Test/use the sqrtViaNewton methods System.out.println("Square root of 2 ~= "+sqrtViaNewton(2.)); System.out.println("Square root of 2 ~= "+sqrtViaNewton(2., 9., 1E-3)); System.out.println("Square root of 3 ~= "+sqrtViaNewton(3., 2., 1E-9)); } }