"only Size-1 Arrays Can Be Converted To Python Scalars"
I have this code: and get this error: TypeError: only size-1 arrays can be converted to Python scalars How can I fix this?
Solution 1:
You can compute y = math.sqrt(R**2 - (x - cc)**2)
as long as x
in a single variable, but in your code you attempt to compute
this expression for each element of xarray (and get an array
of results).
To to this, proceed as follows:
Define your expression as a function:
def myFun(R, x, cc): returnmath.sqrt(R**2 - (x - cc)**2)
Define vectorized version of this function:
myFn = np.vectorize(myFun, excluded=['R', 'cc'])
Compute y as:
y = myFn(R, x, cc)
For R = 20.0
, H = 30.0
and x = np.linspace(-5,5,10)
(a shorter array)
I got:
array([ 8.22875656, 10.34341406, 11.99128261, 13.34639903, 14.49112624,
15.47223243, 16.31925481, 17.05218586, 17.6852162 , 18.22875656])
Solution 2:
I had the same problem/error, what helped me was the answers by Stef and Nils Werner here: Solving only size-1 arrays can be converted to Python scalars error
Basically, you cannot mix .numpy
with .math
functions because they expect different input types (arrays or single integers for numpy functions, but only single integers for math functions).
Post a Comment for ""only Size-1 Arrays Can Be Converted To Python Scalars""