Getting inverse (1 / x) elements of a numpy array

My question is very simple, suppose I have an array like

array = np.array([1, 2, 3, 4]) 

and I would like to get an array like

 [1, 0.5, 0.3333333, 0.25] 

However, if you write something like

 1/array 

or

 np.divide(1.0, array) 

he will not work.

The only way I've found so far is to write something like:

 print np.divide(np.ones_like(array)*1.0, array) 

But I am absolutely sure that there is a better way to do this. Somebody knows?

+6
source share
3 answers

1 / array performs integer division and returns array([1, 0, 0, 0]) .

1. / array will make the array float and do the trick:

 >>> array = np.array([1, 2, 3, 4]) >>> 1. / array array([ 1. , 0.5 , 0.33333333, 0.25 ]) 
+7
source

I tried:

 inverse=1./array 

and it seemed to work ... reason

 1/array 

doesn't work because your array is an integer and 1/<array_of_integers> does integer division.

+1
source

Other possible ways to get the reciprocity of each element of an array of integers:

 array = np.array([1, 2, 3, 4]) 

Using numpy reciprocal:

 inv = np.reciprocal(array.astype(np.float32)) 

Cast:

 inv = 1/(array.astype(np.float32)) 
+1
source

Source: https://habr.com/ru/post/914542/


All Articles