d = (a * b)/ (c * var)
d = Decimal(d).quantize(Decimal('0.01'))
By quantizing d, the above equality does not hold any longer. You've got
to drop that line (your calculator doesn't quantize either).
Stefan Krah
Karsten Goen wrote:
> also this doesn't help, there are still errors in the accuracy. Isn't
there
> a perfect way to do such calculations?
>
Please read the following and see if it helps. Also search the python
users mailing list for something like floating point accuracy, you'll
get plenty of hits.
http://docs.python.org/tutorial/floatingpoint.html
Regards.
Mark Lawrence
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
What is displayed has no influence on rounding errors.
Calculator vendors prevent puzzlement by non-knowledgeable users
by having guard digits. HP apparently deals with professional users,
so I think it not strange at all.
>carries four decimal places, on the assumption that only two are
>significant, and the last two are guards.
>
> Most ALL computers are using IEEE floating point (and the exceptions
>are still a binary floating point, not a decimal representation).
>
> The practice, which /used to be/ taught, is that one does not
>compare floating numbers for equality, but rather one compares the
>difference between floating numbers to be less than some epsilon value;
>epsilon chosen depending upon the significance needed.
>
> Rather than comparing
>
> a = b
>
>one uses
>
> abs(a - b) < epsilon
>
> Since Decimal() also has "infinite" series values (1.0/3.0), an
>epsilon comparison may also be called for.
Not may be.
>--
> Wulfraed Dennis Lee Bieber KD6MOG
Groetjes Albert
--
--
Albert van der Horst, UTRECHT,THE NETHERLANDS
Economic growth -- being exponential -- ultimately falters.
albert@spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst