1

So I created this small python program that finds the root of a number:

def findRoot(number):
    a = 0
    aa = 0.00
    aaa = 0.0000
    aaaa = 0.000000
    aaaaa = 0.00000000
    x = 1
    while x == 1:
        if a * a > number:
            break
        else:
            a = a + 1
    a = a - 1
    aa = aa + a

    while x == 1:
        if aa * aa > number:
            break
        else:
            aa = aa + 0.01
    aa = aa - 0.01
    aaa = aaa + aa

    while x == 1:
        if aaa * aaa > number:
            break
        else:
            aaa = aaa + 0.0001
    aaa = aaa - 0.0001
    aaaa = aaaa + aaa

    while x == 1:
        if aaaa * aaaa > number:
            break
        else:
            aaaa = aaaa + 0.000001
    aaaa = aaaa - 0.000001
    aaaaa = aaaaa + aaaa

    while x == 1:
        if aaaaa * aaaaa > number:
            break
        else:
            aaaaa = aaaaa + 0.00000001
    aaaaa = aaaaa - 0.00000001
    aaaaa = aaaaa + 0.000000009375465
    print(aaaaa)
findRoot(64)
findRoot(81)
findRoot(36)
findRoot(784)

It worked without the numbers behind the decimal mark, with just the first few lines (it would just output 8 as root 64), but now the output is: 7.999999999999999. Where does the 0.000000000000001 go to? And why does it work fine with 81, 36 and 784? Why don't those numbers loose 0.000000000000001 like 64 does?

Djaro
  • 31
  • 7
  • It´s a general issue depending on floating points. float/double vlaues are not exact values and the CPU can´t calculate exact with it. So using `decimal` is the common way or define a rounding +- which is also "correct". – LenglBoy Apr 12 '18 at 13:59
  • Example from java: `double a=Double.MAX_VALUE; double b=Double.MAX_Value - 1;` print both values or use `==` on a IF and you will see it´s the same because it´s not correct. – LenglBoy Apr 12 '18 at 14:02
  • Thank you @LenglBoy , I used the round function and it worked – Djaro Apr 12 '18 at 14:04
  • But so keep in mind that this woun´t be correct for calculating real things. So on Python there are `decimal` types, too. You just need to import them. – LenglBoy Apr 12 '18 at 14:05

0 Answers0