我有一个函数需要针对一系列参数进行计算和可视化。
以下是Jupyter代码的示例:
%pylab
%matplotlib inline
%matplotlib notebook
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
def testFunc(x):
a = x[0] - x[1]
#if a < 0:
# a = 0
b = 2*(a**3)
return b
X = np.arange(100, 10000, 10)
Y = np.arange(3600, 3900, 10)
X, Y = np.meshgrid(X, Y)
Z = testFunc([X, Y])
fig = plt.figure(figsize=(12,8))
ax = fig.gca(projection='3d')
surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm)
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()
但是,我需要向该功能添加其他逻辑:
if a < 0:
a = 0
当我取消注释这些行时,我得到了错误:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-15-273b40ed507a> in <module>()
20 Y = np.arange(3600, 3900, 10)
21 X, Y = np.meshgrid(X, Y)
---> 22 Z = testFunc([X, Y])
23
24 fig = plt.figure(figsize=(12,8))
<ipython-input-15-273b40ed507a> in testFunc(x)
11 a = x[0] - x[1]
12
---> 13 if a < 0:
14 a = 0
15
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
该函数是否在“ a”中应用值数组?因此,它不知道将哪个项目与“ 0”进行比较。
您能推荐一种很好的方法来计算带有条件的函数吗 属性的范围(可能将其可视化)?