How do I get a whole number as a result for a cube root?

后端 未结 6 1869
梦谈多话
梦谈多话 2021-01-13 13:15

I am creating a problem which requires me to find the cube root of certain numbers, some of them have whole number roots, but a lot of them don\'t.

I have numbers li

6条回答
  •  一向
    一向 (楼主)
    2021-01-13 14:02

    The standard way to check for equality with floating point is to check for quality within a certain tolerance:

    def floateq(a, b, tolerance=0.00000001):
        return abs(a-b) < tolerance
    

    Now you can check if the rounded, converted-to-an-integer version of the cube root is equal to the cube root itself within a certain tolerance:

    def has_integer_cube_root(n):
        floatroot = (n ** (1.0 / 3.0))
        introot = int(round(floatroot))
        return floateq(floatroot, introot)
    

    Usage:

    >>> has_integer_cube_root(125)
    True
    >>> has_integer_cube_root(126)
    False
    

    However, this is quite imprecise for your use case:

    >>> has_integer_cube_root(40000**3)
    True
    >>> has_integer_cube_root(40000**3 + 1)
    True
    

    You can mess with the tolerance, but at some point, floating point numbers just won't be enough to have the accuracy you need.

    EDIT: Yes, as the comment said, in this case you can check the result with integer arithmetic:

    def has_integer_cube_root(n):
        floatroot = (n ** (1.0 / 3.0))
        introot = int(round(floatroot))
        return introot*introot*introot == n
    
    >>> has_integer_cube_root(40000**3)
    True
    >>> has_integer_cube_root(40000**3 + 1)
    False    
    

提交回复
热议问题