Warning or error on conversion from complex to float.

Hi, Is it possible or easy to add a warning and/or error when array assignments are made that lose information? I just got caught with the following type of code: def f(): return numpy.array([1j,2.0]) x = numpy.empty((2,),dtype=float) x[:] = f() I am pre-allocating arrays for speed, but made a change to f() resulting in complex results. My code now silently ignores the imaginary part. It would have been very helpful if the assignment check to make sure that the conversion was not going to lose information (presumably with an assert so that performance is not affected outside of debugging). Any simple suggestions on how to avoid this problem in the future? How hard would it be to add such a check in numpy? Thanks, Michael.

On Nov 8, 2007 11:32 AM, Michael McNeil Forbes <mforbes@physics.ubc.ca> wrote:
Hi,
Is it possible or easy to add a warning and/or error when array assignments are made that lose information? I just got caught with the following type of code:
def f(): return numpy.array([1j,2.0])
x = numpy.empty((2,),dtype=float) x[:] = f()
I am pre-allocating arrays for speed, but made a change to f() resulting in complex results. My code now silently ignores the imaginary part. It would have been very helpful if the assignment check to make sure that the conversion was not going to lose information (presumably with an assert so that performance is not affected outside of debugging).
Any simple suggestions on how to avoid this problem in the future? How hard would it be to add such a check in numpy?
This seems to be a generic problem. In [1]: a = empty((10,), dtype=float32) In [2]: a[:] = 10.0 In [3]: a[:] = float32(1) In [4]: b = empty((10,), dtype=float64) In [5]: a[:] = b[:] In the case of the scalar assignments downcasting is a convenience because having to explicitly use the correct data type in an assignment gets to be a hassle when the type isn't native to Python. It might have been more correct to require matching data types, but convenience won out in that case. That said, it might be useful to warn on such an unexpected conversion as complex to float, and maybe for float to integer conversions also. Chuck
participants (2)
-
Charles R Harris
-
Michael McNeil Forbes