Nested loop -TypeError: only size-1 arrays can be converted to Python scalars

Viewed 63

I'm trying to find the max value with two different variables:

    import numpy as np
    import matplotlib.pyplot as plt
    from math import pi, sqrt
    
    i =.5
    l = .01
    u = 4*pi*10**-7
    
    angle = np.linspace(0,pi/2,20)
    d = np.linspace(0,.5, 50)

    B = []

    for ang in angle:
            for dis in d:
                x = (u*i*np.cos(ang))/(pi*sqrt((l/2)**2 + d**2))
                B.append(max(x))

However, it keeps giving me "TypeError: only size-1 arrays can be converted to Python scalars"

I'm not even sure what this means.

1 Answers

Your problem is caused by the math.sqrt() function which tries to get a vector as input: The term related to l is a scalar, while the term related to d is a vector. Usually, Python tries to add the scalar value to each of the entries in the vector, which results in a vector. If this is what you want, you can just replace sqrt of the math package with np.sqrt().

Let's see why this is the case:

The math.sqrt() only take scalars as inputs. It also works, if an array has a size of one, which is then converted to a scalar:

>>> math.sqrt(np.array([4]))
2.0

This is tried in your case, but fails as the term in the brackets is a vector with a size bigger than one. You can try it out in an easier example:

>>> math.sqrt(np.array([9, 25]))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: only size-1 arrays can be converted to Python scalars

In these cases, you can just use numpys sqrt method instead of maths ones:

>>> np.sqrt(np.array([9, 25]))
array([3., 5.])
Related