problem with floats and calculations

Stefan Krah stefan-usenet at bytereef.org
Sun Feb 14 12:42:34 CET 2010


Karsten Goen <karsten.goen at googlemail.com> wrote:
> also this doesn't help, there are still errors in the accuracy. Isn't there a
> perfect way to do such calculations?

The hint I gave you removes the most egregious error in your program.
You still have to quantize the result of (c*var*d) / b) if you want
it to match a. If I adapt your program, I don't find any non-matching
numbers.

for i in range(100000):
    # set random numbers
    a = Decimal(str(random.uniform(0.1,123))).quantize(Decimal('0.01'))
    b = Decimal(str(random.uniform(20.1,3000))).quantize(Decimal('0.01'))
    c = Decimal(str(random.uniform(100, 5000))).quantize(Decimal('0.01'))
    var = Decimal('8.314').quantize(Decimal('0.01'))
    # calc d
    d = (a * b)/ (c * var)
    if ((c*var*d) / b).quantize(Decimal('0.01')) != a:
        print a, (c*var*d) / b


Note that for perfect accuracy you should use the fraction module.


Stefan Krah





More information about the Python-list mailing list