Base 2 Fraction Fiasco
This stuff is fairly basic, and exists as a base for future posts mostly.
If you’re an old, early-twenties fogey such as myself, you can remember back to a time when it cost a few grand to buy a computer which, instead of using a hard disk drive, took floppy disks the size of your head. Still, even in that ancient age, people knew that “computers talk in ones and zeros”. That’s right. If you don’t know the first thing about computers, you still know they speak in binary.
These ones and zeros work really well for integral values, but computers will choke and gag on fractional values more often than you realize. And I’m not just talking about ultra tiny fractions representing the width of a grain of sand in miles… even for simple stuff. Consider the following classic example:
#include <iostream>
int main(int argc, char *argv[])
{
float one_tenth = 0.1f;
float total = 0.0f;
for(int i=0;i<1000;i++)
total += one_tenth;
std::cout << total;
std::cin.get();
}
The program is pretty straightforward. Take a variable (set to 0) and add 0.1 to it a thousand times. If you don’t feel like whipping out a calculator and adding 0.1 over and over again, then trust me–the answer will be 100. So we hit compile, kick back, and get ready to bask in the glow of the 100 that’s about to be printed to our screen:
99.99
Ahh… enjoy that beautiful 100 glow. Wait, 99.99? What? I mean it’s just adding 0.1 a bunch, so there wouldn’t be any rounding errors, right? RIGHT?!?
The price is WRONG!
Continue Reading »