【问题标题】:python: invalid value encountered in true_divide - but where?python:在 true_divide 中遇到无效值 - 但在哪里?
【发布时间】:2017-06-01 19:13:08
【问题描述】:

我有一个关于以下问题的问题:

我想绘制以下简单函数:

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

如果 x & y 为零,你会除以零,所以我添加了一个例外来防止这种情况:

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()

我的数字是情节,如果我检查我的解决方案,它似乎也是正确的。但是,如果我运行代码,则会出现除法错误:

RuntimeWarning: invalid value encountered in true_divide

我已经手动测试了 np.where 函数,它将 x_1=x_2=0 值返回为真。这似乎行得通。

有人知道这个警告来自哪里吗?

【问题讨论】:

  • 我无法复制它。你的代码对我来说很好,并绘制了一个图表
  • np.where() 的参数都是求值的,所以这样使用并不能消除错误。
  • @WarrenWeckesser 如果我理解正确,'x1*x2/(x1*x1+x2*x2)' 也被评估为 x1=x2=0。你知道比 np.where() 更好的方法来解决这个问题吗?

标签: python numpy scientific-computing


【解决方案1】:

正如已经指出的那样,您将使用np.where() 评估每个案例。为了避免错误,只需将其编码在较低级别,例如

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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-06
    • 2018-02-04
    • 1970-01-01
    • 2019-06-12
    • 2020-11-11
    • 2017-07-14
    • 1970-01-01
    相关资源
    最近更新 更多