Cosme Rodolfo Santos
Cosme Rodolfo Santos

Reputation: 13

Matrix divide by zero warning

I am new in Python and I am facing the following error in the code:

import numpy as np
A = np.empty([2, 2], dtype = float)
Z = np.empty([2, 2], dtype = float)
Z = [[2.0, 0.0],  [0.0, 3.0]]
A = [[1, -1], [1, -2]]

print(np.divide(A, np.power(Z, 2)))

These code gives the following result:

[[ 0.25  -inf], [inf -0.22222222]]

But I know, using a calculator, that the correct answer should be:

[[ 0.25   -0.25], [ 0.111111 -0.22222222]]

In short, thhis operation gives me the following error: RuntimeWarning: divide by zero encountered in true_divide

Upvotes: 0

Views: 324

Answers (1)

Ehsan
Ehsan

Reputation: 12397

You are element-wise dividing A by Z^2:

A:

[[1, -1], [1, -2]]

Z^2:

[[4.0, 0.0],  [0.0, 9.0]]

A/Z^2:

[[ 0.25  -inf], [inf -0.22222222]]

The output is correct. You receive the warning (and not an error) of division by 0 because there are 0s in Z^2 in denominator that result in infs in output. Your calculator output is not what your code does.

Upvotes: 0

Related Questions