hi,

i just start to learn and doing programming with python (was an old timer programmer in other languages). when i saw a project idea about creating your own squareroot function, i tried it.

the problem start was when i try to compare the result of

x**2

where x is not an integer. one example that i tried is:

2.2**2 resulting 4.840000000000001

which we all know that is incorrect. i also tried using the math.pow function, but the result is the same.

can anyone help me to solve this problem? thanks.

P.S. I also tried it on python 2.6.2 which results is even more strange (4.8400000000000007)

its because you have a floating point number, im not sure exactly how to fix it but at least you now know the problem

@woooee: Thanks for the info. Exactly what I needed. After twisting with the code and struggling with the syntax, I managed to solve the problem.

@jlm699: 2.2^2 = 4.84 (and not 4.840000000001, try it with a calculator or the google link you gave)

@jlm699: 2.2^2 = 4.84 (and not 4.840000000001, try it with a calculator or the google link you gave)

Yes, but that .000000000001 is obviously due to binary floating-point arithmetic.

>>> '%f' % 2.2**2
'4.840000'
>>> '%.2f' % 2.2**2
'4.84'
>>>

yes.. that im aware of that.. but that wasnt my question to the problem. the question was how to solve it because i needed the exact result for my calculation in the program.

but the problem is solved anyway.

Most computer languages would give you the same problem. The computer tries to represent a floating point number as a binary internally. To compare floating point numbers you need to use fuzzy logic. Here as an function to use:

def fuzzyequals(a, b, delta=0.0000001):
    """
    returns True if a is between b-delta and b+delta
    used for comparison of floating point numbers a and b
    """
    return abs(a-b) < delta

even though i solved the problem with the Decimal() function, and i prefer to solve a problem directly instead of going around a problem, but the fuzzy logic approach is interesting and gave me another point of view. Thanks.

This question has already been answered. Start a new discussion instead.