Search code examples
pythonnumpyscientific-computing

python: invalid value encountered in true_divide - but where?


I have a question regarding the following problem:

I want to plot the following easy function:

f(x) = x_1*x_2/(x_1^2+x_2^2)

If x & y are zero you would divide by zero, so I added an exception to prevent this case:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

def f(x1, x2):
    return np.where(np.logical_and(x1==0,x2==0),
                    0,
                    x1*x2/(x1*x1+x2*x2))

n = 3 
x = y = np.linspace(-5,5,n)
xv, yv = np.meshgrid(x, y)
z = f(xv,yv)

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(xv,yv,z)
plt.show()

My figure is plot and if I inspect my solution it seems also to be correct. However if I run the code I get a division error:

RuntimeWarning: invalid value encountered in true_divide

I tested already the np.where function manually and it returns the x_1=x_2=0 value as true. That seems to work.

Does anybody know where this warning comes from?


Solution

  • As it has been pointed out, you will evaluate every case using np.where(). To avoid the error just code it in a lower level such as

    import numpy as np
    import matplotlib.pyplot as plt
    from mpl_toolkits.mplot3d import Axes3D
    
    def f(x1, x2):
        shape = np.shape(x1) 
        y = np.zeros(shape)
        for i in range(0,shape[0]):
            for j in range(0,shape[1]):
                if x1[i,j]!=0 and x2[i,j]!=0:
                    y[i,j] = x1[i,j]*x2[i,j]/(x1[i,j]*x1[i,j]+x2[i,j]*x2[i,j])
        return y
    
    n = 3 
    x = y = np.linspace(-5,5,n)
    xv, yv = np.meshgrid(x, y)
    z = f(xv,yv)
    
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    ax.plot_surface(xv,yv,z)
    plt.show()