[PYTHON MATRIX-SIG] Proposal: upward cast operation

Konrad HINSEN hinsenk@ere.umontreal.ca
Mon, 4 Mar 1996 13:49:13 -0500


Problem: How do you write a mathematical function that works for
integers, floats, complex numbers, and number classes implemented in
Python? If you think that's easy, look at this example:

  def f(a, b):
    return a/(a+b)

If you call this with integer arguments, it won't do what you think,
because the division operation for integers is different. You might of
course simply say "don't call this with integer arguments", but you
might have to call it with numbers coming from, say, a library
function whose types are not so easy to predict. You could also modify
the code to

  def f(a, b):
    return float(a)/(a+b)

but then it doesn't work for complex arguments, because a gets
replaced by its real part. And for other number types, you don't
even know what float() does. What is needed is a type cast that
acts only "if necessary".


I propose to add two such functions to umath, one to cast to float and
the other to cast to complex. The cast to float should work like
this:
1) If the argument is an integer, cast it to float.
2) If the argument has a suitably named method, call this
   method to do the cast.
3) If neither 1) or 2) apply, return the argument unchanged.

The cast to complex would work similarly, with only the
first step different.

Any comments? Is there a problem I have overlooked? Or is there
a simpler solution to the problem?

-------------------------------------------------------------------------------
Konrad Hinsen                     | E-Mail: hinsenk@ere.umontreal.ca
Departement de chimie             | Tel.: +1-514-343-6111 ext. 3953
Universite de Montreal            | Fax:  +1-514-343-7586
C.P. 6128, succ. Centre-Ville     | Deutsch/Esperanto/English/Nederlands/
Montreal (QC) H3C 3J7             | Francais (phase experimentale)
-------------------------------------------------------------------------------

=================
MATRIX-SIG  - SIG on Matrix Math for Python

send messages to: matrix-sig@python.org
administrivia to: matrix-sig-request@python.org
=================