1

I wrote this function, but I really don't understand why do I have this output.

Function:

double itr = 1.0;

public double findClosestXupper(double xone, double fxone) {
    double xtwo, fxtwo;
    xtwo = xone + itr;
    fxtwo = xtwo - Math.pow(xtwo, 2);
    if(fxone < 0) {
        if(fxtwo < 0) {
            System.out.println("check1 " + xtwo + "    " + fxtwo);
            xtwo = xone - itr;
            fxtwo = xtwo - Math.pow(xtwo, 2);
            System.out.println("check2 " + xtwo + "    " + fxtwo);
            if(fxtwo < 0) {
                itr = itr + 1.0;
                System.out.println("check3 " + xtwo + "    " + fxtwo);
                findClosestXupper(xone, fxone);
            }
        }
    }
    System.out.println("check4 " + xtwo + "    " + fxtwo);
    return xtwo;
}

Output: (having as input xone = 3.2; fxone = 3.2 - 3.2^2 -- negative variable)

check1 4.2    -13.440000000000001
check2 2.2    -2.6400000000000006
check3 2.2    -2.6400000000000006
check1 5.2    -21.840000000000003
check2 1.2000000000000002    -0.2400000000000002
check3 1.2000000000000002    -0.2400000000000002
check1 6.2    -32.24
check2 0.20000000000000018    0.16000000000000011
check4 0.20000000000000018    0.16000000000000011
check4 1.2000000000000002    -0.2400000000000002
check4 2.2    -2.6400000000000006

Why does check4 is displayed three times? From where 000000000000002 comes from? Thank you!

Grigore Dodon
  • 137
  • 3
  • 13
  • 6
    1. because you are using recursion without a return. 2. because doubles are not precise, use [BigDecimal](http://stackoverflow.com/questions/14845937/java-how-to-set-precision-for-double-value) instead – SomeJavaGuy Nov 16 '15 at 12:58

1 Answers1

2

The reason why 'check4' is displayed 3 times is due to the fact that findClosestXupper is being called within its self 3 times. The first time, all cases hold true, and findClosestXupper(xone, fxone); is called. In the second call, all cases hold true again, resulting in a second call to findClosestXupper(xone, fxone);. In the third call, the cases do not hold true, and 'check4' is printed, and then the third call returns. This causes the second call to complete its call and return its 'check4', which then returns and causes the first call to also complete and return the first 'check4'. The reason we see slightly arbitrary trailing decimal values is due to floating point precision. More on that can be found here.

MrPublic
  • 520
  • 5
  • 16