0

I am trying to plot a graph of some calculations however I am receiving a ValueError of the following:

The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I have looked up what the error means, however my question is how that loop interacts with my graphing commands as the issue only arises when I try to graph the results.

Full Code:

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

What I think my code should be doing is calculating values of tolerance between 1e-30 and 1e-2 with 10000 points in between. The log plot takes tolerance as it's independent variable and the dependent variable depends on the values function. The program does not like the way I am writing this and spits out the ValueError (I have manually created my own arrays and plotted the results and they appear accurate so my question is why this error arises from the plotting commands that I used).

The ValueError specifically points to:

if (numpy.absolute((prev_sum - current_sum))) < tolerance:
            return total_sum
A.Torres
  • 413
  • 1
  • 6
  • 16
  • No, the error arises whenever you cal the function and `tolerance` is an array – juanpa.arrivillaga Jan 30 '20 at 19:22
  • 1
    I'm not sure how helpful the duplicate is in this case, so for a basic understanding consider that what you are doing is asking if an array is smaller than a number. However, consider that for e.g. `[1,3] < 2 == [True, False]` no single answer can be given to that question, i.e. some elements may be larger, some not. I'm not sure what exactly that if clause should be doing in your code, but at least it points you to why it won't work as it is. – ImportanceOfBeingErnest Jan 30 '20 at 19:51
  • Prior to that error line, look at the condition calculation, `(numpy.absolute((prev_sum - current_sum))) < tolerance`, with a `print` or print shape. It probably is a numpy boolean array - many True/False values. That's where the ambiguity comes from. The python `if` only works with **one** True/False value, not many. – hpaulj Jan 30 '20 at 21:30

0 Answers0