[Numpy-discussion] Warning or error on conversion from complex to float.
Charles R Harris
charlesr.harris at gmail.com
Thu Nov 8 19:16:23 EST 2007
On Nov 8, 2007 11:32 AM, Michael McNeil Forbes <mforbes at physics.ubc.ca>
> 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 : a = empty((10,), dtype=float32)
In : a[:] = 10.0
In : a[:] = float32(1)
In : b = empty((10,), dtype=float64)
In : 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.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the NumPy-Discussion