[Edu-sig] Re: rationals

Guido van Rossum guido@python.org
Sat, 12 Oct 2002 11:19:49 -0400


> Basically, it boils down to whether we have to use a . (dot) or an r
> to coerce a float or rational result respectively.

Except of course, in reality, the values are in variables, and
possibly we don't even know the types of those variables.

So then you can write

  (x * 1r) / y

to force a rational as long as x and y are ints or rationals; this
yields a float or complex if either x or y is that.

Aside: you could also use

  (x + 0r) / y

but if x is an IEEE float with the value -0, adding 0 turns it into
+0, while multiplying by 1 keeps the sign the same.  The distinction
between +0 and -0 may be important when it is the result of underflow.

For example:

  >>> x = -1.0
  >>> while x:
  ...     x = x*0.5
  ...
  >>> x
  -0.0
  >>> x*1
  -0.0
  >>> x+0
  0.0
  >>> x < 0
  False
  >>> 

--Guido van Rossum (home page: http://www.python.org/~guido/)