Reputation: 103
What is wrong with this, please? I would like to define Cartesian coordinate system, and then I would like to compute Cylindrical coordinate with respect to axis x.
I got an error:
R = math.sqrt(y[i]**2 + z[i]**2)
TypeError: only size-1 arrays can be converted to Python scalars
Code:
import numpy as np
import math
XMIN =-0.15
XMAX = 0.15
YMIN = -0.1
YMAX = 0.1
ZMIN = -0.1
ZMAX = 0.1
sampling = 100
x_ = np.linspace(XMIN, XMAX, sampling)
y_ = np.linspace(YMIN, YMAX, sampling)
z_ = np.linspace(ZMIN, ZMAX, sampling)
x, y, z = np.meshgrid(x_, y_, z_, indexing='ij')
assert np.all(x[:,0,0] == x_)
assert np.all(y[0,:,0] == y_)
assert np.all(z[0,0,:] == z_)
# cylindric coordinates (R, theta, z)
R_coor = []
THETA_coor = []
Z_coor = []
for i in range(sampling-1):
R = math.sqrt(y[i]**2 + z[i]**2)
THETA = math.atan(y[i]/z[i])
Z = x[i]
R_coor.append(R)
THETA_coor.append(THETA)
Z_coor.append(Z)
Upvotes: 0
Views: 1275
Reputation: 149185
Close to a typo.
In the offending line, you are using math.sqrt
which can only operate on scalars. You must use the numpy version np.sqrt
to operate on numpy ndarrays, or use x_, y_, z_
to have scalars.
So you should use either:
for i in range(sampling-1):
R = math.sqrt(y_[i]**2 + z_[i]**2)
THETA = math.atan2(y_[i], z_[i]) # always prefere atan2 to atan...
Z = x_[i]
R_coor.append(R)
THETA_coor.append(THETA)
Z_coor.append(Z)
or:
for i in range(sampling-1):
R = np.sqrt(y[i]**2 + z[i]**2)
THETA = np.arctan2(y[i],z[i])
Z = x[i]
R_coor.append(R)
THETA_coor.append(THETA)
Z_coor.append(Z)
Unrelated, but atan
will break at pi/2 because you get an infinite quotient and can only return angle in the ]-pi/2, pi/2[ open segment, while atan2 can process the whole circle...
Upvotes: 1