Java implementation of Babylonian Method – method to calculate square root of positive numbers.

IN 3 0.0000000001 OUT sqrt(3.0) = 0.3 sqrt(3.0) = 5.15 sqrt(3.0) = 2.86626213592233 sqrt(3.0) = 1.956460731776899 sqrt(3.0) = 1.74492093914502 sqrt(3.0) = 1.7320982711195376 sqrt(3.0) = 1.7320508082191837

import java.util.Scanner; // ? 2018 TheFlyingKeyboard and released under MIT License // theflyingkeyboard.net public class Main { public static void main(String[] args) { double number = 0.0; double precision = 0.0; Scanner scanner = new Scanner(System.in); System.out.println("Enter number to square root"); number = scanner.nextDouble(); System.out.println("Enter precision"); precision = scanner.nextDouble(); if (number < 0) { System.out.println("Number must be >= 0"); return; } if (number == 0) { System.out.println("sqrt(0) = 0"); return; } double x = number / 10; double y = number / x; do { System.out.println("sqrt(" + number + ") = " + x); x = (x + y) / 2; y = number / x; } while (x - y > precision); } }

Java Babylonian Method – SQRT()