incubator-couchdb-user mailing list archives

Site index · List index
Message view
Top
From Leo Simons <m...@leosimons.com>
Subject Re: sum function in reduce with precision problems?
Date Sat, 12 Dec 2009 13:18:41 GMT
```On 12/12/09 12:33 PM, Michael Franzkowiak wrote:
> CouchDB seems to think that 0.79 + 5.99 + 1.59 = 8.370000000000001

So does most other software when using floating point arithmetic:

\$ python -c 'print "%.15f" % (0.79 + 5.99 + 1.59)'
8.370000000000001
\$ perl -e 'print sprintf("%.15f\n", 0.79 + 5.99 + 1.59);'
8.370000000000001
\$ python -c 'print "%.20f" % (0.79 + 5.99 + 1.59)'
8.37000000000000099476
\$ perl -e 'print sprintf("%.20f\n", 0.79 + 5.99 + 1.59);'
8.37000000000000099476

This is standard stuff (
http://docs.sun.com/source/806-3568/ncg_goldberg.html ).

> I could always just multiply my numbers with the precision I need
> and work with ints but I'm still curious to see this explained.

What you really really want is a decimal type:

\$ python -c 'from decimal import Decimal; print Decimal("0.79") +
Decimal("5.99") + Decimal("1.59")'
8.37

...but there is no decimal type in javascript or json so also does not
exist in CouchDB.

Looks like you're representing money; just work with cents (stored as
ints) and you will *probably* be fine, especially if you stay clear of
divisions. I wouldn't try and implement my own finance package that way,
though :)

Alternatively, implement your own decimal type in javascript, or use a
relational database :)

ciao,

Leo

```
Mime
View raw message