python - 具有多个元素的数组的真值是不明确的。绘图时使用 a.any() 或 a.all()
问题描述
我正在尝试绘制一些计算的图表,但是我收到以下 ValueError :
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
我已经查看了错误的含义,但是我的问题是该循环如何与我的绘图命令交互,因为问题仅在我尝试绘制结果时出现。
完整代码:
def compute_with_difference(a, b, tolerance=1e-5):
# By doing some traditional math, we can find that the sum only converges when (a/b) < 1 or (a/b) >= 1
if abs(a / b) >= 1:
raise ValueError()
n = 1
total_sum = 0
prev_sum = 0
current_sum_with_difference = 0;
while True:
current_sum = (b * ((a / b) ** n))
current_sum_with_difference = numpy.absolute(current_sum - (current_sum - prev_sum))
total_sum += current_sum_with_difference
if (numpy.absolute((prev_sum - current_sum))) < tolerance:
return total_sum
prev_sum = current_sum
n += 1
tolerance = numpy.logspace(1e-30, 1e-2, 10000)
plt.loglog(tolerance, compute_with_difference(-2, 3, tolerance), 'b--', linewidth=1)
plt.ylabel('Difference')
plt.xlabel('Tolerance')
plt.show()
我认为我的代码应该做的是计算 1e-30 和 1e-2 之间的容差值,其间有 10000 个点。对数图将容差作为自变量,因变量取决于值函数。该程序不喜欢我写这个的方式并吐出ValueError(我手动创建了自己的数组并绘制了结果,它们看起来很准确,所以我的问题是为什么这个错误是由我使用的绘图命令引起的)。
ValueError 特别指出:
if (numpy.absolute((prev_sum - current_sum))) < tolerance:
return total_sum
解决方案
推荐阅读
- reactjs - 道具如何通过
- python - 如何使用 OOP 在 Python3 中创建一个类以从 Excel 文件加载和读取数据?
- api - 数据覆盖谷歌表 - Jupyter 连接
- javascript - 当点击来自 v 按钮的链接时,Vuetify 工具提示会显示在左上角
- bash - 通配符在 bash 中表示任何但不为空
- python - 文件“kivy\properties.pyx”,第 864 行,在 kivy.properties.ObservableDict.__getattr__ AttributeError: 'super' object has no attribute '__getattr__'
- azure - Azure 函数 - 托管证书
- spring-boot - ZUUL API 网关 RIBBONCLIENT 请求错误
- javascript - 在子窗口中检测到查询参数后如何重新加载父窗口?
- javascript - 反应类组件。待办事项应用程序。如何使用 localStorage 存储数据