Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

The behavior of numpy.fromfunction()

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[[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 ] ]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading