Duncan Booth wrote:
farsi...@gmail.com wrote:
Thanks all, that's very helpful, sorry to waste your time with a
common question. I have tried the decimal module and will definitely
keep using it if I need to do this kind of calculation again.
Try to remember though that the decimal module simply replaces one source
of inaccuracies with another one:
Decimal("1")/Decimal("3")
Decimal('0.3333333333333333333333333333')
_ * 3
Decimal('0.9999999999999999999999999999')
1./3.
0.33333333333333331
_ * 3
1.0
Sometimes you want floating point, sometimes you want Decimal. You need to
understand the advantages and drawbacks of each in order to make an
informed choice.
I have 1 more question that the floating point article that was linked
didn't really answer:
x = 0.8
x
0.800000000000004
x * 5
4.0
Shouldn't I be expecting something like 4.0000000000002 ?
You should certainly expect that the final result may be a little bit away
from the 'exact' result but rounding errors can work in your favour just as
well as they work against.
You should also keep fractions.Fraction (Rational) number in your
toolbox. Rational is the most accurate, though it still can't represent
irrational numbers[1] (e.g. pi, e, phi, sqrt(2)) and is generally slower
than the others.
[1] actually, neither float nor Decimal can represent irrationals.
PS: Actually, I've been thinking about reducing numbers that can't be
represented as float, Decimals, Rationals by adding such things as surds
and special constants. Basically getting python to have exact arithmetic
library, but I think it'll be too large and complex while not many
people really need exact arithmetic.
--
http://mail.python.org/mailman/listinfo/python-list