Search code examples
javarecursionnewtons-method

Newton's method with recursion in Java


I was just curious I have this piece of Java code. My question is what is the reason to return 1.0 * the recursive call? in the else portion of the code

My 2nd question is when I declare the E variable as 0.0000001 AND A , X variables as doubles in my main portion of the code I make the A as 0 and go into an infinite loop. How do I solve this?

public static double sqrtR(long x, double e, double a) {
    if (Math.abs(a * a - x) <= e) {
        return a;
    } else {
        a = (a * a + x) / (2 * a);
        return 1.0 * (sqrtR(x, e, a));
    }
}

Solution

  • When a equals 0 it causes f'(x) = 2a to go to 0 in which case you get division by 0 in this step:

    a = (a * a + x) / (2 * a);
    

    When f'(x) goes to 0, it indicates you are at a minimum or maximum: http://en.wikipedia.org/wiki/Newton%27s_method

    Shifting the value by 1 can work depending upon the equation. In some case there is no zero to the function in which case even if you shifted by 1 Newton's method could push you back to the same optimum. In other cases functions might have many different optima and Newton's method can easily get stuck even when there is a solution such as with some trigonometric functions.

    In your case it should work unless one of two cases is true:

    1. Your equation has no zeros.
    2. Your equation has exactly one zero.

    In case 1, you'll get stuck in the optimum since there is no zeros. In case 2, the zero is at the optimum which will cause the program to go to infinity.

    So first you want to check if your f(x) is zero at that point since you might have found the answer. Else shift off to the side and as long as step size is not too large it should find the zero if there is one.