Student: I was thinking about how
11 / 2 produces 5, and that seems bad. Isn’t there a way to work with fractions? Python just answers 5.5 on that program. Python’s clearly a better language.Prof: I’ll withhold judgment on languages. But we can get decimal numbers in Java.
Student: Oh really?
Prof: Indeed. There is another type we haven’t talked about called
double, which can hold non-integer numbers.Student: I see. Why don’t we just use
double all the time? They can represent whole numbers and decimal numbers, so they seem just better.Prof: Glad you asked. Because of how
doubles are stored in a computer, they have error. It’s kind of like they get rounded off (though the actual way it happens is more complicated than rounding), and the results can be surprising. Imagine you’re charging small fees in a program that handles money. This should produce 0.6 (60 cents if we’re talking dollars):Student: That’s so weird! Why is it doing that?
Prof: It is weird! And this is just a simple, not-so-far-off error. The errors for more complex calculations with multiplication and division can be much worse. So can you tell me why this would be bad for a bank, or for a defense system?
Student: I guess one error isn’t so bad, but if you made a lot of errors they could add up?
Prof: That’s right – a bank that does billions or trillions of microtransactions could start to see real accounting errors. A defense system could miss an incoming missile due to accumulated error. So lots of programs that work with money work with exact
int amounts of cents or other small units, and long-running simulations need to account for error or periodically reset to exact observed values.Student: Hm, so when should I use doubles?
Prof: Well, I think our mass and gravity example is pretty reasonable. Physical simulations, animations, or other cases where the answers are meant to be continuous or approximate anyway are a pretty good fit!
Student: OK, so
double for approximate, decimal calculations. Keep using int for exactness.Prof: That’s a pretty good rule to remember. Both are useful!
Practice
For each of these, pick the type you would use.
The number of students enrolled in a course:
The measured temperature of a room in degrees:
The setting on a thermostat in whole degrees:
A bank balance, kept in cents:
The height of a falling ball in a physics simulation:
The volume of a swimming pool in cubic feet based on its dimensions:
The width of a
The average of several test scores:
The measured temperature of a room in degrees:
The setting on a thermostat in whole degrees:
A bank balance, kept in cents:
The height of a falling ball in a physics simulation:
The volume of a swimming pool in cubic feet based on its dimensions:
The width of a
Pict in pixels: The average of several test scores: