Newton's method with recursion in Java

I'm just curious that I have this piece of Java code. My question is what is the reason for returning a 1.0 * recursive call? in another part of the code

My second question is, when I declare variable E as variable 0.0000001 and variables A, X are doubled in my main body of code, I make A as 0 and go into an infinite loop. How to 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));
    }
}

      

+3


source to share


1 answer


When a is 0, it causes f '(x) = 2a to go to 0, in which case you end up with division by 0 in this step:

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

      

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

Changing the value by 1 may work depending on the equation. In some cases, the function is nonzero, in which case even if you moved Newton's method by 1, you can bring you back to the same optimal one. In other cases, functions can have many different optima, and Newton's method can easily get stuck even when there is a solution, for example with some trigonometric functions.



In your case, this should work if only one of two cases:

  • Your equation has no zeros.
  • Your equation has exactly one zero.

In case 1, you are stuck in optimal since there are no zeros. In case 2, zero is in optimal mode, which will cause the program to go to infinity.

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

+3


source







All Articles