Mongodb lack of precision incrementing floats
Question: I have a problem because Mongodb doesn't seem to maintain precision when
incrementing floats. For example, the following should yield `2.0`:

    
    
    from decimal import Decimal  # for python precision
    for i in range(40):
        db.test.update({}, {'$inc': {'count': float(Decimal(1) / 20)}}, upsert=True)
    print db.test.find_one()['count']
    2.000000000000001
    

How can I get around this issue?


Answer: Unfortunately, you can't -- at least not directly. Mongo stores floating-point
numbers as double-precision IEEE floats
(<https://en.wikipedia.org/wiki/IEEE_floating_point>), and those rounding
errors are inherent to the format.

I'm noticing you're using Decimals in your code -- they're converted to Python
floats (which are doubles) before being sent to the DB. If you want to keep
your true decimal precision, you'll have to store your numbers as stringified
Decimals, which means you'll also have to give up Mongo's number-handling
facilities such as `$inc`.

It is, sadly, a tradeoff you'll be confronted to in most databases and
programming languages: IEEE floating-point numbers is the format CPUs natively
deal with, and any attempts to stray away from them (to use arbitrary-
precision decimals like `decimal.Decimal`) come with a big performance and
usability penalty.

