[Numpy-discussion] Baffling TypeError using fromfunction with explicit cast

Thomas Coffee thomasmcoffee at gmail.com
Sat Dec 24 19:52:46 EST 2011


Nevermind ... did not realize that fromfunction was internally vectorizing
the function over arrays. Solution:


>>> numpy.fromfunction(lambda i, j: (i*j).astype(numpy.float), (3,4))
array([[ 0.,  0.,  0.,  0.],
       [ 0.,  1.,  2.,  3.],
       [ 0.,  2.,  4.,  6.]])



On Sat, Dec 24, 2011 at 7:46 PM, Thomas Coffee <thomasmcoffee at gmail.com>wrote:

> Somewhat new to NumPy, but I've been investigating this for over an hour
> and found nothing helpful:
>
> Can anyone explain why this works ...
>
>
> >>> import numpy
> >>> numpy.fromfunction(lambda i, j: i*j, (3,4))
> array([[ 0.,  0.,  0.,  0.],
>        [ 0.,  1.,  2.,  3.],
>        [ 0.,  2.,  4.,  6.]])
>
>
> ... but neither of these do?
>
>
> >>> numpy.fromfunction(lambda i, j: float(i*j), (3,4))
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
>   File "/usr/lib/pymodules/python2.7/numpy/core/numeric.py", line 1617, in
> fromfunction
>     return function(*args,**kwargs)
>   File "<stdin>", line 1, in <lambda>
> TypeError: only length-1 arrays can be converted to Python scalars
>
>
> >>> numpy.fromfunction(lambda i, j: numpy.float(i*j), (3,4))
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
>   File "/usr/lib/pymodules/python2.7/numpy/core/numeric.py", line 1617, in
> fromfunction
>     return function(*args,**kwargs)
>   File "<stdin>", line 1, in <lambda>
> TypeError: only length-1 arrays can be converted to Python scalars
>
>
> Given that fromfunction casts the return values to float by default, why
> does it break when this cast is made explicit?
>
> The motivation for the question is to be able to use fromfunction with a
> function that can return infinity, which I only know how to create with the
> explicit cast float('inf').
>
> Thanks in advance for your help!
>
> - Thomas
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20111224/288c160d/attachment.html>


More information about the NumPy-Discussion mailing list