Python – use ints instead of floats

floating pointintpythonpython-3.x

I'm preparing for a class lesson (I'm teaching) and I'm trying to predict any possible questions from the students and I ran into one that I can't answer:

If we have floats, why do we ever use ints at all? What's the point?

I know (or at least I think) that floats take more memory because they have more accuracy, but surely the difference is nearly negligible as far as memory usage goes for most non-embedded applications.

And I realize in many cases we actually don't need a float, but honestly, why do we have ints in the first place? What's the point? There's nothing an int can do that a float can't.

So why are they there at all?

Edit: You could argue they're easier to write (3 vs. 3.0) but you could just make all numbers default to float, so 3 would be treated the same as 3.0. Why make it a different type?

Best Answer

Floating point numbers are approximations in many cases. Some integers (and decimals) can be exactly represented by a float, but most can't. See Floating Point Arithmetic: Issues and Limitations.

>>> a = 1000000000000000000000000000
>>> a+1 == a
False
>>> a = 1000000000000000000000000000.0
>>> a+1 == a
True

Resulting from this approximative nature of floats, some calculations may yield unexpected results (this isn't directly pertinent to the question, but it illustrates the point quite well):

>>> sum(1.1 for _ in range(9))
9.899999999999999

For example, when you're dealing with money calculations, it's better to use integers, or (if speed is not an issue) the decimal module.