Does python suck or I am just stupid?

Stephen Horne intentionally at blank.co.uk
Sat Feb 22 22:06:39 CET 2003


On 22 Feb 2003 10:00:16 -0800, andy at takecover.net (Andy Mroczkowski)
wrote:

>I've been tearing my hair out over a bug(?) I've come across.

>                if u == x:

>What is wrong?  Is this some weird feature?  Or is Python broken?  And
>sorry if this is something silly that I'm overlooking on my part.


Previous answers (esp Peter Hansons, with the link) should explain
what is going on - but the 'epsilon' solution from the FAQ is not
always the best.

Sometimes, there is a way to get perfect precision with fractional
values - the two approaches are (1) fixed point arithmetic and (2)
rational arithmetic.

Fixed point is implemented by using integer numbers, but adopting a
convention for scaling. The classic example is that $1.01 can equally
be represented as 101 cents. Ideally, a language feature would hide
this integer representation in applications where the scaling is an
annoyance.

Rational arithmetic simply means using (frequently top-heavy)
fractions. In a sense, the principle is similar to fixed point
arithmetic but the 'scaling' is variable so you need two integers (the
value and the scale) for each number.

Fixed point is more efficient, whereas rational arithmetic is more
flexible.

Python doesn't directly support either at the moment (there are
regular murmurings, but there are some technical issues too) though
there may well be a library or two somewhere - wander over to
www.python.org and check the links. There are a few languages that
directly support these approaches, but not really the most widely used
languages - Python cannot really be knocked for not (yet) providing
these features.

However, it's probably not a big problem to use the 'fixed point'
approach directly in your source code - adopt a scaling of 1000 (to
give 3 decimal places in the 'logical' value) and you shouldn't have
too many problems. Just remember to keep the scale factor correct with
operations such as multiplication and division (e.g. a * b // 1000
instead of just a * b).

In some languages, the maximum value of an integer might give you a
headache when the scale factor causes overflows - in Python, long
integers remove that headache.

-- 
steve at ninereeds dot fsnet dot co dot uk




More information about the Python-list mailing list