Java Programming

Square Root

Java programming example for square root without sqrt

9/26/2021
0 views
square-root.javaJava
/* 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
Java programmingsquare rootsqrt method

Loading comments...

Related Examples

Deliver breaking news, insightful commentary, and exclusive reports.

Targeting readers who rely on our platform to stay ahead of the curve.

Contact Us: benzingaheadlines@gmail.com