【问题标题】:Finding the distance between two points in 3D space, Python查找3D空间中两点之间的距离,Python
【发布时间】:2022-08-14 07:34:32
【问题描述】:

我有一个任务问题。根据问题的情况,给出两个坐标为 xyz 的点 p1、p2,你需要使用类在 3D 空间中求出这些点之间的距离。任务本身似乎很简单,但对我来说,困难在于距离的计算必须使用只有一个距离(其他)参数的方法进行,我不明白如何做到这一点,如果需要两个变量,它们将给出两个点的坐标,在方法中我们只能使用一个。

我试图这样做,但我收到一个错误(不支持的操作数类型 -:\'str\' 和 \'str\'):

from math import sqrt


class Point3D:
    x: float
    y: float
    z: float

    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z

    @staticmethod
    def distance(other):
        return sqrt((other[0][0] - other[1][0]) ** 2 + (other[0][1] - other[1][1]) ** 2 + (other[0][2] - other[1][2]) ** 2)

p1 = [1, 2, 3]
p2 = [3, 2, 1]
s1 = Point3D(*p1)
s2 = Point3D(*p2)
print(Point3D.distance((s1, s2)))

>>>unsupported operand type(s) for -: \'str\' and \'str\'

我也尝试这样做,但它给出了一个错误(\'str\'对象没有属性\'x\')

# The rest of the code is the same

@staticmethod
    def distance(other):
        return sqrt((other[0].x - other[1].x) ** 2 + (other[0].y - other[1].y) ** 2 + (other[0].z - other[1].z) ** 2)

p1 = [1, 2, 3]
p2 = [3, 2, 1]
s1 = Point3D(*p1)
s2 = Point3D(*p2)
print(Point3D.distance((s1, s2)))

>>>AttributeError: \'str\' object has no attribute \'x\'

还有可以正常工作但不被接受的代码,因为距离需要 2 个参数,但需要 1 个(这是他们不接受我的代码的示例):

# The rest of the code is the same

 def distance(self, other):
        return sqrt((other.x1 - self.x1) ** 2 + (other.y1 - self.y1) ** 2 + (other.z1 - self.z1) ** 2)
 
p1 = [1, 2, 3]
p2 = [3, 2, 1]
point1 = Point3D(*p1)
point2 = Point3D(*p2)
print(point1.distance(point2))

>>>2.8284271247461903

请帮我修复代码,以便它与 distance(other) 方法一起使用并且不会引发错误。如果需要,您可以删除 @staticmethod。老实说,我不知道该怎么办了。我会很高兴得到任何帮助

  • 你好丹尼尔,欢迎来到 StackOverflow!似乎最后一段代码是正确的,并且只接受你演示的一个参数。 self 参数不需要传入,它指的是方法的“所有者”(在本例中为 point1)。
  • 还有,你是当然在第一个和第二个 sn-ps 中的代码是你写的吗?因为我在代码中的任何地方都看不到str 或任何字符串。当我运行 sn-p 1 时,我得到了错误TypeError: \'Point3D\' object is not subscriptable,这更有意义。

标签: python coordinates


【解决方案1】:

您的代码和错误不匹配。

当我尝试你的代码时,它会导致以下异常:

TypeError: 'Point3D' object is not subscriptable

这是可以理解的,因为Point3D 不是序列类型。

此外,您在长途电话中有多余的括号,因此您基本上只给它一个参数(一个 2 元组)。

尝试这个:

from math import sqrt


class Point3D:
    def __init__(self, x, y, z):
        self.x = float(x)
        self.y = float(y)
        self.z = float(z)

    def distance(self, p2):
        return sqrt((self.x - p2.x) ** 2 + (self.y - p2.y) ** 2 + (self.z - p2.z) ** 2)


s1 = Point3D(1, 2, 3)
s2 = Point3D(3, 2, 1)
print(s1.distance(s2))

【讨论】:

  • 不,事实是我不需要距离(self,p),而只需要距离(p),即只有一个参数。这是任务的条件(
  • distance的来电。只使用了一个参数(s2)...
猜你喜欢
  • 2019-09-16
  • 2016-07-21
  • 1970-01-01
  • 1970-01-01
  • 2019-03-28
  • 2015-08-16
  • 2012-09-01
  • 2023-01-20
  • 1970-01-01
相关资源
最近更新 更多