绘制具有给定约束的函数时没有出现表面

No surface appear when plotting a function with given constraints

import matplotlib.pyplot as plt
from matplotlib import cm
from numpy import nan, linspace, meshgrid
x1=linspace(0,2,50)
x2=linspace(0,2,50)
x1, x2 = meshgrid(x1, x2)
f=((x1+1.5)**2+5*(x2-1.7)**2)*((x1-1.4)**2+0.6*(x2-0.5)**2)
f[-x1<=0] = nan
f[-x2<=0] = nan
f[3*x1-x1*x2+4*x2-7<=0] = nan
f[2*x1+x2-3<=0] = nan
f[3*x1-4*x2**2-4*x2<=0] = nan
fig, ax = plt.subplots(subplot_kw={"projection": "3d"})
ax.plot_surface(x1, x2, f, cmap=cm.jet,linewidth=0, antialiased=False,label="Kurva $f(x_1,x_2)$",alpha=1)
ax.set_xlabel('$x_1$')
ax.set_ylabel('$x_2$')
ax.set_zlabel('$f(x_1,x_2)$')
plt.show()

我要剧情f=((x1+1.5)**2+5*(x2-1.7)**2)*((x1-1.4)**2+0.6*(x2-0.5)**2) 具有给定的 5 个约束条件:

当我运行上面的代码时,图中什么也没有出现。我的错误是什么?如何解决?

您将 x1x2 定义为:

x1=linspace(0,2,50)
x2=linspace(0,2,50)

所以它们的每个值都在02之间。然后你编辑它们:

x1, x2 = meshgrid(x1, x2)

此时x1x2不再是数组,而是矩阵。不管怎样,和以前一样,它们里面的每个元素仍然在02之间。
如果您应用此过滤器:

f[-x1<=0] = nan

然后 f 的每个元素变为 nan,因为 x1 的所有元素都是正数,所以表达式 -x1<=0 对每个元素的计算结果为 False x1 的元素。同样的逻辑适用于过滤器:

f[-x2<=0] = nan

所以,确实,f 的每个元素都是 nan 并且情节是空的。
如果您尝试删除上述两个过滤器,则会得到:

f[3*x1-x1*x2+4*x2-7<=0] = nan
f[2*x1+x2-3<=0] = nan
f[3*x1-4*x2**2-4*x2<=0] = nan