从平方米计算墙长

乘风 python 252

原文标题Calculating Wall Length From Square Metres

给定一个大于 1 且小于 10^18 的整数,表示平方米,计算墙的总长度。精确到最多 10^-6 的绝对或相对误差。

例如,给定 10000 应该返回 400.000000000000000,给定 8921796 应该返回 11947.750248477744273。

我目前的解决方案,第一次测试失败但其他测试通过。这与四舍五入有关吗?例如添加 0.000000000000001 使第一次测试通过(例如注释掉)

from decimal import Decimal

def getWallLength(metreSqr: int) -> str:
    result =  Decimal(metreSqr) ** Decimal(0.5) * Decimal(4) 
    # result + Decimal(0.000000000000001)
    return str(round( result, 15 ))



def testWallLength(metreSqr: int, expected: int):
    if ((result := getWallLength(metreSqr)) == expected):
        print("Passed: got " + str(result) + " should be " + str(expected))
    else:
        print("Failed: got " + str(result) + " should be " + str(expected))

def runTests():
    testWallLength(8921796, '11947.750248477744273')
    testWallLength(10000, '400.000000000000000')
    testWallLength(2233, '189.018517611370553')


if __name__ == "__main__":
    runTests()

失败:得到 11947.750248477744272 应该是 11947.750248477744273
通过:得到 400.000000000000000 应该是 400.000000000000000
通过:得到 189.018517611370553 应该是 189.018517611370553

原文链接:https://stackoverflow.com//questions/71476553/calculating-wall-length-from-square-metres

回复

我来回复
  • ramzeek的头像
    ramzeek 评论

    您所说的失败的答案实际上是计算机(或至少是我的计算机)的浮点限制。引用关于浮点运算的文档:

    停在任何有限的位数,你会得到一个近似值。在当今的大多数机器上,浮点数使用二进制分数来近似,分子使用前 53 位,从最高有效位开始,分母为 2 的幂。

    Python 提供的工具可以在您确实想知道浮点数的确切值的极少数情况下提供帮助。 float.as_integer_ratio() 方法将浮点数的值表示为分数。

    如果我们查看您的“失败”数字和您的测试认为它“应该”的数字,您可以看到它们都由相同的分数表示:

    11947.750248477744272.as_integer_ratio()
    # (6568345161982437, 549755813888)
    11947.750248477744273.as_integer_ratio()
    # (6568345161982437, 549755813888)
    (8921796**0.5 * 4).as_integer_ratio()
    # (6568345161982437, 549755813888)
    
    2年前 0条评论