<br><br><div class="gmail_quote">On Nov 8, 2007 11:32 AM, Michael McNeil Forbes <<a href="mailto:firstname.lastname@example.org">email@example.com</a>> wrote:<br><blockquote class="gmail_quote" style="border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; padding-left: 1ex;">
Hi,<br><br>Is it possible or easy to add a warning and/or error when array<br>assignments are made that lose information? I just got caught with<br>the following type of code:<br><br>def f():<br> return numpy.array([1j,
2.0])<br><br>x = numpy.empty((2,),dtype=float)<br>x[:] = f()<br><br>I am pre-allocating arrays for speed, but made a change to f()<br>resulting in complex results. My code now silently ignores the<br>imaginary part. It would have been very helpful if the assignment
<br>check to make sure that the conversion was not going to lose<br>information (presumably with an assert so that performance is not<br>affected outside of debugging).<br><br>Any simple suggestions on how to avoid this problem in the future?
<br>How hard would it be to add such a check in numpy?<br></blockquote><div><br>This seems to be a generic problem. <br><br>In : a = empty((10,), dtype=float32)<br><br>In : a[:] = 10.0<br><br>In : a[:] = float32(1)
<br><br>In : b = empty((10,), dtype=float64)<br><br>In : a[:] = b[:]<br><br>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.