The idea behind floating point is to abstract away the concept of the an integral and quotient parts of a real number. However, it cannot abstract away the reality of processor design; where registers have a fixed and finite number of bits typically 32 or 64. To see how bad an approximation float, doubleand even decimal make of real-number operations doesn’t take much effort:

For example, the following:

Update: The code snippet below has a typo which prints out the wrong value for decimal. (Pointed out by Stu in comments). Decimal has 128-bits of precision making far more suitable for financial applications.

Will output this:

Ouch, not very precise. In fact float falls over at 1000 iterations of 0.001 because of it smaller 32-bit precision.

This is a trumped-up example but it makes the point and these discrepancies are even greater when divisions or multiplications are done of numbers that vary greatly in magnitude.

So gaving floatingpoint a try in Python:

Much better! My fp object has ruthlessly ignored the first addition because it fell outside its precision of 6, but has exactly the correct value after the summation. So whats the cost of this accuracy? Speed; the above takes many seconds to execute.

The above example involves a million fixed point additions which may seem silly but in a financial setting Monte Carlo simulation models (to name just one) rely on executing many millions of calculations as quickly as possible.

Conclusion

When you need speed; go for floating point. When you need accuracy; go for fixed.

FYI, FixedPoint should be considered deprecated in favor of decimal, which is now included in the standard Python distribution.

http://docs.python.org/lib/module-decimal.html

Python decimal module is a faithful implementation of IEEE 854 standard, and is tested against comprehensive test suite provided by IBM.

Thanks for the info sanxiyn. I’ll check out decimal.

There is a bug in the code. The thrid write line is printing the double, not the decimal as you inteded. That would impact your output.

Thanks Stu, you’re completely right. In fact I was a bit shocked that decimal preformed so badly. I should have looked a bit more carefully!