Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python checking if a point is in sphere with center x, y ,z

Tags:

python

I'm trying to check if a point is within a sphere with a center point of (x, y, z) where (x, y, z) is not (0, 0, 0).

This code I'm using to generate the points I want to check:

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 function are called in a for loop to generate the points in a dictionary, while also checking the unlikely chance that points aren't placed on top of another(mostly because I can).

I trying to figure out what I need to add to math.sqrt(x * x + y * y + z * z) so that it accounts for a center that isn't (0, 0, 0). I do know of one way to do it, but it would require several lines of code and I'd rather do it in one. I would have asked this in the comments of the answer in another question, but I'm not allowed to comment on answers yet.

like image 591
Eegxeta Avatar asked Nov 08 '14 15:11

Eegxeta


1 Answers

The formula is:

A point (x,y,z) is inside the sphere with center (cx,cy,cz) and radius r if

 (x - cx)^2 + (y - cy)^2 + (z - cz)^2 < r^2 
like image 148
JE42 Avatar answered Oct 29 '22 23:10

JE42