  # numpy.reciprocal () in Python

NumPy | Python Methods and Functions

numpy.reciprocal (x, /, out = None, *, where = True): this math function is used to calculate the reciprocal of all elements of the input array.

` Parameters: `

x [array_like] : Input array or object whose elements needed to test.

out [ndarray, optional] : A location into which the result is stored.
- & gt ; If provided, it must have a shape that the inputs broadcast to.
- & gt; If not provided or None, a freshly-allocated array is returned.

** kwargs: Allows to pass keyword variable length of argument to a function. Used when we want to handle named argument in a function.

where [array_like, optional]: True value means to calculate the universal functions (ufunc) at that position, False value means to leave the value in the output alone.

` Return: `
y: ndarray. This is a scalar if x is a scalar.

Note: For integer arguments with an absolute value greater than 1, the result is always zero due to the way Python handles integer division. For integer zero, the result is an overflow.

### Code #1:

```# Python3 code demonstrate reciprocal() function

# importing numpy
import numpy as np

in_num = 2.0
print ("Input  number : ", in_num)

out_num = np.reciprocal(in_num)
print ("Output number : ", out_num)
```

### Output #1:

```Input  number :  2.0
Output number :  0.5
```

### Code #2:

```# Python3 code demonstrate reciprocal() function

# importing numpy
import numpy as np

in_arr = [2., 3., 8.]
print ("Input array : ", in_arr)

out_arr = np.reciprocal(in_arr)
print ("Output array : ", out_arr)
```

### Output #2:

Input array : [2.0, 3.0, 8.0] Output array : [ 0.5 0.33333333 0.125 ]

### Code #3: Exception in reciprocal() function. Result is always zero.

```# Python3 code demonstrate Exception in reciprocal() function

# importing numpy
import numpy as np

in_arr = [2, 3, 8]
print ("Input array : ", in_arr)

out_arr = np.reciprocal(in_arr)
print ("Output array : ", out_arr)
```

### Output #3:

```Input array :  [2, 3, 8]
Output array :  [0 0 0]
```

### Example #4

```def update_rho(self, rho_new):
"""
Update set-size parameter rho
"""
if rho_new <= 0:
raise ValueError("rho must be positive")

# Update rho
self.work.settings.rho = np.minimum(np.maximum(rho_new,
RHO_MIN), RHO_MAX)

# Update rho_vec and rho_inv_vec
ineq_ind = np.where(self.work.constr_type == 0)
eq_ind = np.where(self.work.constr_type == 1)
self.work.rho_vec[ineq_ind] = self.work.settings.rho
self.work.rho_vec[eq_ind] = RHO_EQ_OVER_RHO_INEQ * self.work.settings.rho
self.work.rho_inv_vec = np.reciprocal(self.work.rho_vec)

# Factorize KKT
self.work.linsys_solver = linsys_solver(self.work)
```

### Example #5

```def forward(self, inputs):
self.retain_inputs((0, 1, 2, 4))
x, gamma, mean, var, gy = inputs
expander = self.expander
xp = backend.get_array_module(x)

if self.inv_std is None or self.inv_var is None:
self.inv_var = xp.reciprocal(var + self.eps)
self.inv_std = xp.sqrt(self.inv_var, dtype=self.inv_var.dtype)

self.gamma_over_std = gamma * self.inv_std
x_hat = _x_hat(x, mean[expander], self.inv_std[expander])

gx = self.gamma_over_std[expander] * gy
gbeta = gy.sum(axis=self.axis, dtype=gamma.dtype)
ggamma = (x_hat * gy).sum(axis=self.axis)
gmean = -self.gamma_over_std * gbeta
gvar = - 0.5 * self.inv_var * (
gamma * ggamma).astype(var.dtype, copy=False)

gx = gx.astype(dtype=x.dtype)

self.retain_outputs((0, 1, 2, 3, 4))
return gx, ggamma, gbeta, gmean, gvar
```

### Example #6

```def compute_cooccurrence_constraint(self, nodes):
"""
Co-occurrence constraint as described in the paper.

Parameters
----------
nodes: np.array
Nodes whose features are considered for change

Returns
-------
np.array [len(nodes), D], dtype bool
Binary matrix of dimension len(nodes) x D. A 1 in entry n,d indicates that
we are allowed to add feature d to the features of node n.

"""

words_graph = self.cooc_matrix.copy()
D = self.X_obs.shape
words_graph.setdiag(0)
words_graph = (words_graph > 0)
word_degrees = np.sum(words_graph, axis=0).A1

inv_word_degrees = np.reciprocal(word_degrees.astype(float) + 1e-8)

sd = np.zeros([self.N])
for n in range(self.N):
n_idx = self.X_obs[n, :].nonzero()
sd[n] = np.sum(inv_word_degrees[n_idx.tolist()])

scores_matrix = sp.lil_matrix((self.N, D))

for n in nodes:
common_words = words_graph.multiply(self.X_obs[n])
idegs = inv_word_degrees[common_words.nonzero()]
nnz = common_words.nonzero()
scores = np.array([idegs[nnz == ix].sum() for ix in range(D)])
scores_matrix[n] = scores
self.cooc_constraint = sp.csr_matrix(scores_matrix - 0.5 * sd[:, None] > 0)
```

### Example #7

```def vector_normalize(v):
"""
Normalise (Euclidean) the last axis of a numpy array

:param v: numpy vector array, any dimension
:return:  array normalized, 0 vectors will be np.nan

"""
if v.ndim < 2:
return np.array((1.,))
vs = v.shape
v = v.reshape((-1, v.shape[-1]))
mag = np.linalg.norm(v, axis=1)
mag[mag == 0.] = np.nan
return (v.T * np.reciprocal(mag)).T.reshape(vs)
```

### Example #8

```def predict_proba(X, classifier):
"""Probability estimation for OvR logistic regression.
Positive class probabilities are computed as
1. / (1. + np.exp(-classifier.decision_function(X)));
multiclass is handled by normalizing that over all classes.
"""
prob = np.dot(X, classifier['coef_'].T) + classifier['intercept_']
prob = prob.ravel() if prob.shape == 1 else prob
prob *= -1
np.exp(prob, prob)
prob += 1
np.reciprocal(prob, prob)
if prob.ndim == 1:
return np.vstack([1 - prob, prob]).T
else:
# OvR normalization, like LibLinear's predict_probability
prob /= prob.sum(axis=1).reshape((prob.shape, -1))
return prob
```

### Example #9

```def l1_inverse(depth1,depth2):
"""
Computes the l1 errors between inverses of two depth maps.
Takes preprocessed depths (no nans, infs and non-positive values)

depth1:  one depth map
depth2:  another depth map

Returns:
L1(log)

"""
assert(np.all(np.isfinite(depth1) & np.isfinite(depth2) & (depth1 > 0) & (depth2 > 0)))
diff = np.reciprocal(depth1) - np.reciprocal(depth2)
num_pixels = float(diff.size)

if num_pixels == 0:
return np.nan
else:
return np.sum(np.absolute(diff)) / num_pixels
```

### Example #10

```def ComputeMassMatrixInfo(self, M, formulation, fem_solver):
"""Computes the inverse of lumped mass matrix and so on
"""

invM = None
if formulation.fields == "electro_mechanics":
if fem_solver.mass_type == "lumped":
M = M.ravel()
invM = np.zeros_like(M)
invM[self.mechanical_dofs] = np.reciprocal(M[self.mechanical_dofs])
M_mech = M[self.mechanical_dofs]
else:
M_mech = M[self.mechanical_dofs,:][:,self.mechanical_dofs]
else:
if fem_solver.mass_type == "lumped":
M = M.ravel()
M_mech = M
invM = np.reciprocal(M)
else:
M_mech = M

return M_mech, invM
```