首页 > 解决方案 > 具有多个元素的数组的真值是不明确的。绘图时使用 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

标签: pythonnumpymatplotlibnumerical-methodsscientific-computing

解决方案


推荐阅读