Let's say I have a numpy array like this (positions_full) which load some coordinate data like 2.5 or 8.2. I now wanted to loop that array through the def isInside. How can I do this?
positions_full = np.loadtxt('positions.txt')
x = positions_full[:,0]
y = positions_full[:,1]
def isInside(circle_x, circle_y, rad, x, y):
if ((x - circle_x) * (x - circle_x)
(y - circle_y) * (y - circle_y) <= rad * rad):
return True;
else:
return False;
x = 2.5
y = 8.2
circle_x = 0;
circle_y = 5;
rad = 2;
if(isInside(circle_x, circle_y, rad, x, y)):
print(x,y,rad,"Inside");
else:
print(x,y,rad,"Outside");
CodePudding user response:
I think it is better to use numpy's vectorization. You can make your function isInside
to return a numpy array of boolean values. Then you can just loop outside of the function with a common for-loop. Something like this:
import numpy as np
positions = np.array([[2.5, 8], [3, 10], [0, 5], [1, 5]])
x = positions[:, 0]
y = positions[:, 1]
def isInside(circle_x, circle_y, rad, x, y):
return ((x - circle_x) ** 2 (y - circle_y) ** 2) <= rad ** 2
circle_x = 0;
circle_y = 5;
rad = 2;
for is_inside in isInside(circle_x, circle_y, rad, x, y):
print ("Inside" if is_inside else "Outside")