I’ve been teaching my sons Java by watching the Udacity course “Introduction to Programming: Problem Solving with Java” with them. In lesson four, we were introduced to the vagaries of floating-point arithmetic. The instructor talks about how this calculation
double pennies = 4.35 * 100;
produces 434.99999999999994 as its output.
I told my kids “it has to do with binary numbers” and “I write about this all the time on my blog”. Now of course I know this trips people up, but it really struck me to see the reaction firsthand. (I have long since forgotten my own first reaction.) It really hit home that thousands of new programmers are exposed to this every day.
The solution the instructor first proposed was to convert the result to an integer:
int pennies = (int) (4.35 * 100);
But as he notes, this doesn’t work — it produces 434; you must round the result:
int pennies = (int) Math.round(4.35 * 100);
At this point my ten-year old asked “Why can’t Java do that?”
Why CAN’T Java Do That?
The reason is largely historical. Java syntax is based on C, and C was invented when computers were primitive and there weren’t millions of mainstream programmers. It was OK — probably even necessary — to expose the native workings of the machine to its sophisticated users.
If we were to design a new programming language today, would we make decimal arithmetic the default? Floating-point is really an optimization, for people who know what they’re doing. Make the experts ask for it explicitly. Make the experts use a floating-point class and code things like
if (num.compareTo(zero) > 0)
num = num.add(num1.multiply(two));
Let the rest of us use built-in decimal and instead code
if (num > 0)
num = num + num1 * 2;
By The Way, Why Am I Teaching Them Java?
Java is the first programming language I am teaching them (I’m not counting the hour or so we spent last year with Scratch, which we found too limiting). Don’t read into this as my endorsement of Java as a first programming language. I picked it primarily because they love Minecraft, and wanted to know how to make mods for it. (I don’t know if they’ll ever get to making mods, but at least they will have learned to program.) They also know that Android apps are written in Java, which was my secondary motivation.