Home > Blockchain >  No surface appear when plotting a function with given constraints
No surface appear when plotting a function with given constraints

Time:01-23

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

enter image description here

I want to plot f=((x1 1.5)**2 5*(x2-1.7)**2)*((x1-1.4)**2 0.6*(x2-0.5)**2) with given 5 constraints:

  • -x1<=0
  • -x2<=0
  • 3*x1-x1*x2 4*x2-7<=0
  • 2*x1 x2-3<=0
  • 3*x1-4*x2**2-4*x2<=0

When I run the code above, nothing appear in the figure. What is my mistake? How to fix it?

CodePudding user response:

You define x1 and x2 as:

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

so each value of them is between 0 and 2. Then you edit them with:

x1, x2 = meshgrid(x1, x2)

At this point, x1 and x2 are no longer arrays, but matrices. Anyway, as before, each element within them is still between 0 and 2.
If you apply this filter:

f[-x1<=0] = nan

then each element of f becomes nan, since all elements of x1 are positive, so the expression -x1<=0 evaluates to False for every element of x1. The same logic applies for the filter:

f[-x2<=0] = nan

So, indeed, every element of f is nan and the plot is empty.
If you try to remove both of the above filters, then you get:

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

enter image description here

  •  Tags:  
  • Related