I'm implementing Babylonian method to approximate the square root of number n
using following formula :
nextGuess = (lastGuess + n / lastGuess) / 2;
So when nextGuess
and lasGuess
are almost identical, nextGuess
is the approximated square root.
What am doing is checking if nextGuess
and lastGuess
is less than very small number such as 0.0001
then i can claim that nextGuess
is the approximated square root of n
. if not nextGuess
become lastGuess
.
So how i can implement that in the right way?
My current code:
public static void getApproximatedSquare(long n){
DecimalFormat decimalFormat = new DecimalFormat("#.####");
decimalFormat.setRoundingMode(RoundingMode.CEILING);
double lastGuess = 1, nextGuess;
nextGuess = (lastGuess + n / lastGuess) / 2;
Double init = 0.0001;
System.out.println(decimalFormat.format(init));
if (Double.valueOf(decimalFormat.format(nextGuess)) <= init)
//todo
}