Python check if point is in sphere centered on x, y, z
I'm trying to check if a point is in a sphere with a center point (x, y, z) where (x, y, z) is not (0, 0, 0).
This code I am using to generate the points I want to test:
def generatecoords(self, i):
x, y, z = generatepoint()
if i >= 1:
valid = False
while valid == False:
coords = self.checkpoint(x, y, z)
for b in world.starlist:
if coords == world.starlist[b].coords:
coords = self.checkpoint(x, y, z)
else:
valid = True
else:
coords = self.checkpoint(x, y, z)
return coords
def checkpoint(self, x, y, z):
d = math.sqrt(x * x + y * y + z * z)
while d >= self.radius:
x, y, z = generatepoint()
d = math.sqrt(x * x + y * y + z * z)
coords = (int(x), int(y), int(z))
return coords
def generatepoint():
x, y, z = [int(random.uniform(-self.radius, self.radius)) \
for b in range(3)]
return x, y, z
These functions are called in the for loop to create points in the dictionary, and also check for the likelihood that the points will not be placed on top of another (mostly because I can).
I'm trying to figure out what I need to add to math.sqrt(x * x + y * y + z * z)
so that it takes into account a center that is not (0, 0, 0)
. I know of one way to do this, but it will take several lines of code, and I would rather do it in one. I would have asked this in the comments to the answer in another question, but I am not yet allowed to comment on the answers.
source to share
Here is a very short function that returns True
if point is in a sphere, and False
if not.
Input data are two arrays: point = [x,y,z]
and ref = [x,y,z]
, and the radius must be float
.
import numpy as np
def inSphere(self, point, ref, radius):
# Calculate the difference between the reference and measuring point
diff = np.subtract(point, ref)
# Calculate square length of vector (distance between ref and point)^2
dist = np.sum(np.power(diff, 2))
# If dist is less than radius^2, return True, else return False
return dist < radius ** 2
source to share