Recursive Square Root Finder

I'm having an issue with a method that is trying to find the square root of the number. The previousG is a randomly generated number. The number is the square roots actual number. I'm getting a stack overflow error. I realize why since I'm not updating the nextGuess variable. I'm wondering what I should add to the FindTheRoot method to stop this. Furthermore, I'm doing this recursively.

public static void main(String[] args) {

        int srootArray[] = {9, 17, 25, 37, 49, 55, 999};

        Random randomGuess = new Random();

        for (int index = 0; index < srootArray.length; index++)
        {
            int previousGuess = randomGuess.nextInt(srootArray[index] + 1);
            System.out.println("Number: " + srootArray[index] + "... " + 
"First Guess: " + previousGuess);

            FindTheRoot(previousGuess, srootArray[index]);


            System.out.println("--------------------------------------------
------");
        }

    }

    public static double FindTheRoot(double previousG, int number)
    {
        double errorMargin = 0.00001;
        double nextGuess = (previousG + number / previousG) / 2;

        if (nextGuess < errorMargin)
            return nextGuess;
        else
        {
        System.out.printf("%S%.4f%n", "Next Guess: " , nextGuess);
        FindTheRoot(nextGuess, number);
    }

    return nextGuess;
}

}

1 answer

  • answered 2017-11-12 20:14 Kevin Peña

    You are not comparing the correct number against the error margin, the error of a guess would be (guess * guess) - number (the difference between squaring your guess and the number you would get if your guess were correct) so you need something along the lines of:

    public static double FindTheRoot(double previousG, int number)
    {
        double errorMargin = 0.00001;
        double nextGuess = (previousG + number / previousG) / 2;
        double error = nextGuess * nextGuess - number;
    
        if (error < errorMargin)
            return nextGuess;
        else
            // ...