Sun Sep 26 2021
Square Root
Java Programming947 views
File Name: square-root.java
/* Without using sqrt() */
import java.io.*;
import java.util.Scanner;
class sqroot {
/* Constructor of the class */
sqroot(double no) {
/* Relative error tolerance */
double epsilon = 1e-15;
/* Estimate of the square root of 'no' */
double a = no;
/* Repeatedly apply Newton update step until desired precision is achieved */
while(Math.abs(a - no / a) > epsilon * a) {
a = (no / a + a) / 2.0;
}
System.out.println("Square root of "+no+" = "+a);
}
}
class squareroot {
public static void main(String args[ ]) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number to calculate square root:");
new sqroot(Double.parseDouble(input.nextLine()));
}
}
/* Output */
Enter a number to calculate square root:
2
Square root of 2.0 = 1.414213562373095
Reference:
Author:Geekboots