Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package newton_sqrt;
- //importing Scanner AND Math
- import java.util.Scanner;
- import java.lang.Math;
- //class
- public class Newton_square_root {
- //here's main!
- public static void main(String [] args) {
- //declaring new scanner
- Scanner keyboard=new Scanner(System.in);
- //
- System.out.print("Enter in N for Newton: ");
- int N=keyboard.nextInt();
- //this is defining the variables
- double n=(double)N;
- double last_guess=n/(double)2;
- double new_guess;
- double accuracy;
- double x;
- double absolute_value_of_x;
- x = 0;
- //while N
- while(true)
- {
- //this is how we do the math (math is <0.000001 within range
- //area under the curve etc etc
- new_guess=((n/last_guess)+last_guess)/(double)2;
- accuracy=Math.abs(new_guess-last_guess);
- //accuracy should be close
- if(accuracy<0.000001)
- break;
- last_guess=new_guess;
- //dealing with the absolute value of x
- if (x >=0) {
- absolute_value_of_x = x;
- }
- else {
- absolute_value_of_x = -x;
- }
- }
- //printing out the results
- System.out.println("Newton(200.0)="+new_guess);
- System.out.println("Math.sqrt="+Math.sqrt(n));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement