Issue
I was trying to create different arrays using Numpy's fromfunction()
. It was working fine until I faced this issue. I tried to make an array of ones using fromfunction()
(I know I can create it using ones()
and full()
) and here is the issue :
array = np.fromfunction(lambda i, j: 1, shape=(2, 2), dtype=float)
print(array)
Surprisingly, the output of this function is this :
1
Which is expected to be :
[[1. 1.]
[1. 1.]]
When I change the input function by adding zero times i
, It works just fine.
array = np.fromfunction(lambda i, j: i*0 + 1, shape=(2, 2), dtype=float)
print(array)
The output of this code is :
[[1. 1.]
[1. 1.]]
My main question is how does fromfunction()
actually behaves? I passed the same function with 2 different representations and the output is completely different.
Solution
The callable function is passed two arrays, not repeatedly called with two numbers:
i=[ [ 0.0, 0.0 ],
[ 1.0, 1.0 ] ]
j=[ [ 0.0, 1.0 ],
[ 0.0, 1.0 ] ]
It returns what it is asked to provide ... just ONCE ... to be the ultimate result of np.fromfunction.
So an input of 1 returns just 1 whereas an input of i*0+1 returns
[ [ 0.0, 0.0 ],
[ 1.0, 1.0 ] ] * 0 + 1
which is the (broadcast) array
[ [ 1.0, 1.0 ],
[ 1.0, 1.0 ] ]
Answered By - lastchance
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.