在 python 中修复立方根计算器

Fix Cube Root Calculator in python

cube_Num = float(input(" X: "))
cube_Pow = 0.333
cube_Root = cube_Num**cube_Pow
print(" Result: " + str(round(cube_Root)))

现在,如果我输入 216,它会给出答案 6,这是正确的,但如果我输入 215,它会再次给出 6,我知道我使用舍入函数,因为我将功率提高到 0.333,大约是 1/3.Is 有办法得到数字的实际立方根,例如小数形式的 215 吗?

请注意,完美的立方根答案只有在我使用舍入函数时才是正确的。我希望完全立方根是整数而不是浮点数,而不是完全立方根是小数形式。

喜欢 216 = 6 和 215 = 5.9

round中您可以决定要保留多少位小数。您还应该使用 1/3 而不是 0.333

cube_num = float(input('X: '))
cube_pow = 1/3
cube_root = cube_num ** cube_pow
print(f'Result: {round(cube_root, 4)}')
# Result: 6.3496

如果您使用 f 字符串,您也可以避免转换回 str

round() 方法有两个参数:

number - the number that is to be rounded

ndigits (Optional) - number up to which the given number is to be rounded

在Python中,如果你只使用没有ndigits参数的round(),它会四舍五入为一个整数。

固定码:

cube_Num = float(input(" X: "))
cube_Pow = 0.333
cube_Root = cube_Num**cube_Pow
print(" Result: " + str(round(cube_Root, 2)))

X: 255

Result: 6.33

首先,没有办法得到像十进制 255 这样的数字的实际立方根,因为它们是无理数。其次,6x6x6 等于 216,而不是 256。第三,如果你想要十进制数,为什么要使用 round 函数?也使用 cube_Pow= 1/3。 256 和 255 的最终输出都是 6,因为你正在对 6.329 这样的数字进行四舍五入。这是您可以使用的代码:

cube_Num = float(input(" X: "))
cube_Pow = 1/3
cube_Root = cube_Num**cube_Pow
print(" Result: " , cube_Root)

Note that perfect cube root answers are correct.

不,不总是。

>>> 216**(1/3)
5.999999999999999

编辑:好的,我写了那个,它适用于 216、27 等小型完美立方体:

import math
cube_Num = float(input(" X: "))
cube_Pow = 1/3
cube_Root = cube_Num**cube_Pow

floor = math.floor(cube_Root)

if floor**3 == cube_Num:
    print(floor)
elif (floor+1)**3 == cube_Num:
    print(floor+1)
else:
    print(cube_Root)

如果您需要计算整数的精确立方根,则必须进行整数运算;没有办法解决这个问题。浮点运算不够精确,无法给出正确的立方根,即使正确的立方根 可以精确表示为浮点数。问题是 1/3 不能完全表示为浮点数,并且 ** 对浮点数的操作不能对精度做出强有力的保证(不像基本的算术运算,它保证正确的舍入)。

所以这里有一个使用二分搜索算法的解决方案,它完全通过整数运算工作,并且总是给出准确的结果:int_cube_root(x) 的结果保证是真实立方根的整数部分,即正确答案四舍五入为零。

如果您想要完美立方体的精确答案,但非完美立方体的近似十进制答案,您可以将最后一行 return sign * b 替换为 return sign * x ** (1/3)

def int_cube_root(x):
    if x >= 0:
        sign = 1
    else:
        x = -x
        sign = -1

    a, b = 0, x
    while a <= b:
        m = (a + b) // 2
        m3 = m * m * m

        if m3 == x:
            return sign * m
        elif m3 < x:
            a = m + 1
        else:
            b = m - 1

    # uncomment for decimal answers when x is not a perfect cube
    # return sign * x ** (1/3)

    return sign * b

测试:

>>> int_cube_root(216)
6
>>> int_cube_root(215)
5
>>> int_cube_root(-27)
-3
>>> int_cube_root(-26)
-2
>>> int_cube_root(77777777777777777777 ** 3)
77777777777777777777
>>> int_cube_root(77777777777777777777 ** 3 - 1)
77777777777777777776