Stefan Parenta
Stefan Parenta

Reputation: 1

How are data types interpreted, calculated, and/or stored?

In python, suppose the code is:

import.math

a = math.sqrt(2.0)

if a * a == 2.0:
    x = 2
else:
    x = 1

Upvotes: 0

Views: 42

Answers (2)

Troy Wray
Troy Wray

Reputation: 1018

Numbers with decimals are stored as floating point numbers and they can only be an approximation to the real number in some cases.

So your comparison needs to be not "are these two numbers exactly equal (==)" but "are they sufficiently close as to be considered equal".

Fortunately, in the math library, there's a function to do that conveniently. Using isClose(), you can compare with a defined tolerance. The function isn't too complicated, you could do it yourself.

math.isclose(a*a, 2, abs_tol=0.0001)
>> True

Upvotes: 1

hunteke
hunteke

Reputation: 3716

This is a variant of "Floating Point Numbers are Approximations -- Not Exact".

Mathematically speaking, you are correct that sqrt(2) * sqrt(2) == 2. But sqrt(2) can not be exactly represented as a native datatype (read: floating point number). (Heck, the sqrt(2) is actually guaranteed to be an infinite decimal!). It can get really close, but not exact:

>>> import math
>>> math.sqrt(2)
1.4142135623730951
>>> math.sqrt(2) * math.sqrt(2)
2.0000000000000004

Note the result is, in fact, not exactly 2.

If you want the x = 2 branch to execute, you will need to use an epsilon value of "is the result close enough?":

epsilon = 1e-6    # 0.000001
if abs(2.0 - a*a) < epsilon:
    x = 2
else:
    x = 1

Upvotes: 2

Related Questions