Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should I use ints instead of floats?

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?

like image 918
temporary_user_name Avatar asked Dec 08 '13 10:12

temporary_user_name


2 Answers

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.

like image 96
Tim Pietzcker Avatar answered Nov 23 '22 01:11

Tim Pietzcker


It's important to use data types that are the best fit for the task they are used for. A data type may not fit in different ways. For instance, a single byte is a bad fit for a population count because you cannot count more than 255 individuals. On the other hand a float is a bad fit because many possible floating point values have no meaning. For example, 1.5 is a floating point value that has no meaning as a count. So, using an appropriately sized integer type gives us the best fit. No need to perform sanity checks to weed out meaningless values.

Another reason to favour integers over floats is performance and efficiency. Integer arithmetic is faster. And for a given range integers consume less memory because integers don't need to represent non-integer values.

Another reason is to show intent. When a reader of the code sees that you used an integer, that reader can infer that the quantity is only meant to take integer values.

like image 38
David Heffernan Avatar answered Nov 23 '22 01:11

David Heffernan