Let's say I have a system of two concenctric circles and a numpy array with some coordinates. I now want to check if the coordinates are inside the ring and if so I want to print the respective values for example [6, 0], yes? How can I do this? This is what I have done so far but this leads to the following error: TypeError: only size-1 arrays can be converted to Python scalars
import math
import numpy as np
positions = np.array([[2.5, 8], [3, 10], [0, 5], [6, 0]])
x1 = positions[:, 0]
y1 = positions[:, 1]
# Function to check if array coordinate
# lies in the ring
def checkcircle(r, R, r1, x1, y1):
dis = int(math.sqrt(x1 * x1 y1 * y1))
return (dis-r1 >= R and dis r1 <= r)
r = 8; R = 4; r1 = 2;
if (checkcircle(r, R, r1, x1, y1)):
print([{x1}, {y1}]," yes")
else:
print("no")
CodePudding user response:
Your solution was going in the right direction till you passed the points as scalars and they were actually 2D numpy arrays. I have rewritten your code with some modifications and clarifications as to what does what.
import math
import numpy as np
# points to check
positions = np.array([[2.5, 8], [3, 10], [0, 5], [6, 0],[2,1]])
# Function to check if points lies in the ring
def checkcircle(r, R, positions):
#initialize list to store points that lie in the ring
points_in_ring = []
# Go through every point and check its distance from center assuming, the center lies at (0,0) and can be changed later on
for i in range(positions.shape[0]):
# Calculate euclidean distance between two points
dis = math.dist(positions[i],[0.,0.])
# Print distance for more clarity
print(dis)
# If distance is more than inner radius and less than outer radius, store that point in the list
if dis > R and dis <r:
points_in_ring.append(positions[i])
return points_in_ring
r = 8; R = 4;
checkcircle(r,R, positions)
The math.dist() method returns the Euclidean distance between two points (p and q), where p and q are the coordinates of that point.
Note: The two points (p and q) must be of the same dimensions.
output:
8.381527307120106
10.44030650891055
5.0
6.0
2.23606797749979
[array([0., 5.]), array([6., 0.])]