import numpy as np
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib.pyplot as plt
y = [4, 2]
def objectivedraw(a, b, y):
return -1 * (y[0] + 0.75 * max((1 - b) * y[0] - (y[1] + a), 0) - 0.5 * max((y[1] + a) - (1 - b) * y[0], 0) \
+ y[1] + 0.75 * max((1 - b) * y[1] - (y[0] + a), 0) - 0.5 * max((y[0] + b) - (1 - b) * y[1], 0))
a = np.arange(0, 3.0, 0.1)
b = np.arange(0, 1, 0.1)
A, B = np.meshgrid(a, b) # grid of point
Z = objectivedraw(A, B,y) # evaluation of the function on the grid
fig = plt.figure()
ax = fig.gca(projection='3d')
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1,
cmap=cm.RdBu, linewidth=0, antialiased=False)
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()
这是我正在使用的代码。与绘图相关的部分,即定义Z后,从https://dzone.com/articles/how-plot-function-two(网站上的第二块代码)开始处理。我收到一条错误消息:
File "C:/Users/rohan/PycharmProjects/untitled/plot utility.py", line 12, in objectivedraw
+ y[1] + 0.75 * max((1 - b) * y[1] - (y[0] + a), 0) - 0.5 * max((y[0] + b) - (1 - b) * y[1], 0))
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
我想不出怎么修理它。我想这是因为我的功能
编辑:我想做一个费尔-施密特效用函数,这就是这个函数
对于
Z = objectivedraw(A, B, y)
要使用A
和B
作为(2D)numpy数组,并且Z
也是一个numpy数组,函数objectivedraw
应该与numpy兼容。在numpy中,数组上的函数是逐元素执行的,例如np.sin(A)
将具有与A
相同的元素数和维度数,但所有元素都被其正弦替换@np.vectorize
修饰符可以使函数矢量化。要与numpy兼容,max
运算符应替换为np.maximum
。而且,矢量化不知道如何处理列表y
。在这种情况下y
的元素可以逐个传递相关问题 更多 >
编程相关推荐