簡體   English   中英

如何使用 Python 查找兩個磁盤之間的距離

[英]How to find distance between two disks using Python

在這段代碼中,我需要返回兩個磁盤之間的面積、直徑和距離。 一切似乎都很好,除了我不斷收到距離公式的值錯誤。 距離任務如下:

distance(self, other)計算並返回兩個磁盤之間的距離。 給定圓盤 1 和 2,其中有中心 (,) 和半徑,1 和 2 之間的距離是 0 和 √(1−2)^2+(1−2)^2 − 1 − 2 的最大值。

from math import pi, sqrt
    
class Disk:
    def __init__(self, r, x, y):
        self.radius = r
        self.centre_x = x
        self.centre_y = y
        if r < 0:
           raise ValueError 

    def __repr__(self):
        return "Disk({}, {}, {})".format(self.radius, self.centre_x, self.centre_y)
    
    def diameter(self):
        return (self.radius*2)
    
    def area(self):
        return (pi*(self.radius**2))
    
    def distance(self, other):
        return sqrt((other.centre_x - self.centre_x)**2 + (other.centre_y - self.centre_y)**2)

有人可以幫我解釋一下為什么我不斷收到距離的值錯誤嗎?

您是否嘗試過顛倒減法的順序? 假設self = x1other = x2 你真正想要的是:

        return sqrt((self.centre_x - other.centre_x)**2 + (self.centre_y - other.centre_y)**2)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM