Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Newton Square Root Problem, program that computes the square root of numbers from user input
- // Renee Waggoner
- // June 24, 2019
- // Special Requirements: None
- package newton_sqrt;
- import java.util.Scanner;
- public class NewtonSqrt {
- public static void main(String[] args) {
- // x is for accuracy
- // n the number of times to calculate square root
- double estimate, newtonOutput = 0, n, x;
- Scanner userInput = new Scanner(System.in);
- System.out.println("Enter in N for Newton: ");
- // storing user number for calculation
- n = userInput.nextInt();
- // initial guess
- estimate = n / 2;
- do {
- // computing a better guess
- newtonOutput = ((n/estimate) + estimate)/2;
- x = Math.abs(estimate - newtonOutput);
- // if true, break
- // number of decimals here determine decimal range of answer
- if (x < .000001)
- {
- // my notes: remember break won't work outside of do or switch
- break ;
- } else {
- // otherwise do this
- estimate = newtonOutput;
- }
- // while this statement is true, do the next calculations
- } while (n >= .000001);
- {
- // putting user number in + decimal + answer
- System.out.println("Newton("+n+") = " + newtonOutput);
- // returns the correctly rounded positive square root of a double value
- double mth = Math.sqrt(n);
- System.out.println("Math.sqrt = " + mth);
- }
- userInput.close();
- }
- }
Add Comment
Please, Sign In to add comment