[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.python

Re: problem with floats and calculations

Stefan Krah

2/14/2010 11:43:00 AM

Karsten Goen <karsten.goen@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