Search code examples
javasqrt

why can't I find sqrt using this code?


I tried finding a way to get a sqrt without built-ins and came up ith this, unfortunately it won't work and I have no idea why

    double num=0;
    while ((num*num)!=this.first)
        num=num+0.0001;
    return num;

Solution

  • Ripped from Google:

    What is floating point error?
    The most common situation is illustrated by the decimal number 0.1.
    Although it has a finite decimal representation, in binary it has an
    infinite repeating representation. Thus when = 2, the number 0.1 lies
    strictly between two floating-point numbers and is exactly representable
    by neither of them.
    

    So, filling in your example of 9, your loop probably looked like:

    num = 0; add 0.0001 -> num is now 0.000099999999
    add 0.0001 -> num is now 0.000199999999998
    add 0.0001 -> num is now 0.000299999999997
    etc...
    add 0.0001 -> num is now 2.9999999999953667
    add 0.0001 -> num is now 3.000099999994321
    

    And so, your exact comparison to 3 will not match.