Advertisement
geographconcept

newton's square problem

Apr 7th, 2020
249
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.27 KB | None | 0 0
  1. package newton_sqrt;
  2.  
  3. //importing Scanner AND Math
  4. import java.util.Scanner;
  5. import java.lang.Math;
  6.  
  7. //class
  8. public class Newton_square_root {
  9.    
  10.     //here's main!
  11.     public static void main(String [] args) {
  12.        
  13.                 //declaring new scanner
  14.                 Scanner keyboard=new Scanner(System.in);
  15.                
  16.                 //
  17.                 System.out.print("Enter in N for Newton: ");
  18.                 int N=keyboard.nextInt();
  19.                
  20.                 //this is defining the variables
  21.                 double n=(double)N;
  22.                 double last_guess=n/(double)2;
  23.                 double new_guess;
  24.                 double accuracy;
  25.                 double x;
  26.                 double absolute_value_of_x;
  27.                 x = 0;
  28.                
  29.                 //while N
  30.                 while(true)
  31.                 {
  32.                     //this is how we do the math (math is <0.000001 within range
  33.                     //area under the curve etc etc
  34.                     new_guess=((n/last_guess)+last_guess)/(double)2;
  35.                     accuracy=Math.abs(new_guess-last_guess);
  36.                    
  37.                     //accuracy should be close
  38.                     if(accuracy<0.000001)
  39.                         break;
  40.                     last_guess=new_guess;
  41.                    
  42.                     //dealing with the absolute value of x
  43.                     if (x >=0) {
  44.                         absolute_value_of_x = x;
  45.                     }
  46.                     else {
  47.                         absolute_value_of_x = -x;
  48.                     }
  49.                 }
  50.                
  51.                
  52.                
  53.                 //printing out the results
  54.                 System.out.println("Newton(200.0)="+new_guess);
  55.                 System.out.println("Math.sqrt="+Math.sqrt(n));
  56.                 }
  57.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement