letsdoitjava

Newton Square Root

Jun 23rd, 2019
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.39 KB | None | 0 0
  1. // Newton Square Root Problem, program that computes the square root of numbers from user input
  2. // Renee Waggoner
  3. // June 24, 2019
  4. // Special Requirements: None
  5.  
  6. package newton_sqrt;
  7. import java.util.Scanner;
  8.  
  9. public class NewtonSqrt {
  10.  
  11.     public static void main(String[] args) {
  12.         // x is for accuracy
  13.         // n the number of times to calculate square root
  14.         double estimate, newtonOutput = 0, n, x;
  15.  
  16.         Scanner userInput = new Scanner(System.in);
  17.         System.out.println("Enter in N for Newton: ");
  18.         // storing user number for calculation
  19.         n = userInput.nextInt();
  20.         // initial guess
  21.         estimate = n / 2;
  22.  
  23.         do {
  24.             // computing a better guess
  25.             newtonOutput = ((n/estimate) + estimate)/2;
  26.             x = Math.abs(estimate - newtonOutput);
  27.            
  28.             // if true, break
  29.             // number of decimals here determine decimal range of answer
  30.             if (x < .000001)
  31.             {
  32.                 // my notes: remember break won't work outside of do or switch
  33.                 break ;
  34.                
  35.             } else {
  36.                 // otherwise do this
  37.                 estimate = newtonOutput;
  38.             }
  39.            
  40.             // while this statement is true, do the next calculations
  41.         } while (n >= .000001);
  42.         {
  43.             // putting user number in + decimal + answer
  44.             System.out.println("Newton("+n+") = " + newtonOutput);
  45.             // returns the correctly rounded positive square root of a double value
  46.             double mth = Math.sqrt(n);
  47.             System.out.println("Math.sqrt = " + mth);
  48.         }
  49.         userInput.close();
  50.     }
  51. }
Add Comment
Please, Sign In to add comment