chamathabeysinghe
chamathabeysinghe

Reputation: 868

Why is the is_integer() method not working?

I wrote this code in Python:

x=345**3
z=float(x)**(1.0/3.0)
print z
print z.is_integer()

The output is:

345.0
False

Why is that? I expected the output to be True.

Upvotes: 1

Views: 3768

Answers (2)

jonrsharpe
jonrsharpe

Reputation: 122023

Because z isn't exactly 345.0:

>>> x = 345 ** 3
>>> z = float(x) ** (1.0 / 3.0)
>>> print z
345.0
>>> (345.0).is_integer()
True

All good so far, however:

>>> z.is_integer()
False
>>> z == 345.0
False
>>> z
344.9999999999999

This is just a display issue, due to the difference in str and repr forms of float:

>>> z.__repr__()
'344.9999999999999'
>>> z.__str__()
'345.0'

Upvotes: 6

CIsForCookies
CIsForCookies

Reputation: 12817

You are raising a non-integer to the power of a non-integer, so the result is a non-integer

Upvotes: 0

Related Questions