[MATRIX-SIG] Float32 and type conversions.

Konrad Hinsen hinsen@ibs.ibs.fr
Thu, 18 Dec 1997 11:44:28 +0100


> I'm trying to do something like this and it fails:
> 
>     a = ones([5,5], Float32)
>     a[2:4] = a[2:4] * 0.5
> 
> Python prints the error message:
> 
>     TypeError: Array can not be safely cast to required type
> 
> Of course I understaind what goes wrong! Is there any way
> around this problem? Is there any way to make python or NumPy
> tread 0.5 (or any other number for that matter) as a float and
> not as a double? I'm asking this because it is really important 

Plain numbers don't exist as float in Python. You have two choices:

1) Put the factor 0.5 into an array of shape (1,) of type float:

      a = ones([5,5], Float32)
      half = array([0.5], Float32)
      a[2:4] = a[2:4] * half

2) Cast the result of the multiplication back to float:

      a = ones([5,5], Float32)
      a[2:4] = (a[2:4] * 0.5).astype(Float32)

The second method produces a double intermediary, which may be a problem
if your arrays are very big.
-- 
-------------------------------------------------------------------------------
Konrad Hinsen                          | E-Mail: hinsen@ibs.ibs.fr
Laboratoire de Dynamique Moleculaire   | Tel.: +33-4.76.88.99.28
Institut de Biologie Structurale       | Fax:  +33-4.76.88.54.94
41, av. des Martyrs                    | Deutsch/Esperanto/English/
38027 Grenoble Cedex 1, France         | Nederlands/Francais
-------------------------------------------------------------------------------

_______________
MATRIX-SIG  - SIG on Matrix Math for Python

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