3

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));
    }
}
Nayuki
  • 17,911
  • 6
  • 53
  • 80
linyu21
  • 81
  • 10
  • Could you also supply sample input and output? – Rafiek Jun 08 '15 at 04:20
  • public static void main(String[] args) { double x=2; double e=0.0000001; double a=1; System.out.println("The Square Root of X is" + sqrtR(x,e,a)); } } – linyu21 Jun 08 '15 at 04:22
  • i might have figured it out , how would i add an iteration count? – linyu21 Jun 08 '15 at 04:23
  • 1
    Multiplying by 1.0 has absolutely no effect. It can be simplified. – Nayuki Jun 08 '15 at 04:37
  • how so? i am still a little unsure what the 1.0 does would you please elaborate on that? – linyu21 Jun 08 '15 at 04:41
  • 1
    What do you mean, you're unsure what 1.0 "does"? The code tries to multiply something by 1, which is pointless. What part don't you understand? Somebody may have thought they had a good reason to do this, but they were wrong. – ajb Jun 08 '15 at 04:52

1 Answers1

3

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.

Hazok
  • 5,373
  • 4
  • 38
  • 48
  • alright so I should just set a to 1 as an initial guess value? – linyu21 Jun 08 '15 at 04:37
  • Depends on 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. Will update the answer with more detail. – Hazok Jun 08 '15 at 04:43