Python检查一个点是否在以x,y,z为中心的球体中

2024-10-01 07:22:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着检查一个点是否在一个中心点为(x,y,z)的球体内,其中(x,y,z)不是(0,0,0)。在

我用来生成要检查的点的代码:

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

在for循环中调用这些函数来生成字典中的点,同时也检查点不太可能被放在另一个上面的可能性(主要是因为我可以)。在

我试图找出我需要添加到math.sqrt(x * x + y * y + z * z)中的内容,以便它占一个不是(0, 0, 0)的中心。我知道有一种方法可以做到这一点,但这需要几行代码,我宁愿用一行代码来完成。我会在另一个问题的答案的评论中问这个问题,但我现在还不能评论答案。在


Tags: 代码selffalseforreturnifdefmath
2条回答

公式为:

一个点(x,y,z)在圆心(cx,cy,cz)和半径r的球体内

 (x - cx)^2 + (y - cy)^2 + (z - cz)^2 < r^2 

这是一个非常短的函数,如果点在球体中,则返回True,如果不是,则返回False。在

输入是两个numpy数组:point = [x,y,z]和{},半径应该是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

相关问题 更多 >