5 ms·
Years ago there was a triangle problem on an ACM Scholastic Programming Contest. It looked simple. Given three lengths, output whether that forms a triangle or
by ja27 12y ago
Years ago there was a triangle problem on an ACM Scholastic Programming Contest. It looked simple. Given three lengths, output whether that forms a triangle or not and whether it's a right triangle or isosceles triangle. Simple right? A^2 + B^2 = C^2.
Most programmers that were naive about floating-point got burned. One item in the test data set (which they kept hidden and ran against your program and you only got a pass/fail result) would fail the simple equality case if you used a double-precision float but would pass if you used a single-precision. Lots of learning took place.
- jacquesm 12y agoWhen doing tests for equality with fp you should always test against a difference and an epsilon. like this: // in C if (fabs(v1 - v2) < epsilon) { // equal } else { // unequal } And epsilon should be chosen with some care, as in: understand your problem domain and run exhaustive tests to make sure you got it right. Test cases should include 'just below', 'on' and 'just above' cases. Even better if you convert your values to some non-floating point numbers. As they say, if you need floats you don't understand your problem (yet). Obviously that doesn't always apply but it applies more often than you might think at first.
- pjungwir 12y ago> understand your problem domain It sounds like the article's explanation of how precision erodes as the number increases would help a lot when thinking about this. A good epsilon is a function of the size of your numbers. I've been writing a lot of money-related code lately in C with long doubles, so floating point has been on my mind, and this article is timed perfectly. According to my tests I can get past $36 billion before I see $0.000001 error, which I think is good enough for me, but I should revisit my reasoning now that I understand things better!
- AndrewOMartin 12y agoYou may want to use a more intuitively behaving datatype for currency, even if just to avoid flame on certain community sites on the web. Consider an integer representing ten-thousandths of a penny, if guaranteed to stay in USD or GBP, or a dedicated currency library otherwise. Currency's just one of those things that makes some people very emotional when the notion of any kind of error or rounding is mentioned.
- lightcatcher 12y agoI'm not very experienced in representing money in computer programs, but I thought the best practice was to store all values as integers (using either cents or smaller as your unit). Any reason you chose to use doubles instead of integers or longs?
- jacquesm 12y agoThe best way to represent money is as fixed point integers. 64.64 would be a good start, you can adjust that up/down with more knowledge about your application.