"Only size-1 arrays can be converted to Python scalars"

Viewed 15492

I have this code:

R = float(input("Enter the arc's radius of curvature: "))
H = float(input("Enter the arc's height: "))

import matplotlib.pyplot as plt
import numpy as np
import math

#cc = center of curvature
cc = math.sqrt(R**2 - (H / 2)**2)
x = np.linspace(-5,5,100)
y = math.sqrt(R**2 - (x - cc)**2)
plt.plot(x, y, 'c')
plt.show()

and get this error:

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

How can I fix this?

3 Answers

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 x array (and get an array of results).

To to this, proceed as follows:

  1. Define your expression as a function:

     def myFun(R, x, cc):
         return math.sqrt(R**2 - (x - cc)**2)
    
  2. Define vectorized version of this function:

     myFn = np.vectorize(myFun, excluded=['R', 'cc'])
    
  3. 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])

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

See the solution below:

import numpy as ny
import matplotlib.pyplot as matplot

xcord = ny.arange(1, 5, 2.5)
ycord = ny.vectorize(ny.int)
matplot.plot(xcord, ycord(xcord))
matplot.show()

To see the full code explanation check here.

Related