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

后端 未结 6 1899
梦谈多话
梦谈多话 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条回答
  •  萌比男神i
    2021-01-13 14:12

    The result of 125 ** (1.0/3.0) is never going to be an integer because that is a floating-point operation. This is much easier to do by looking at the cube instead. For instance, if you just want the largest number with an integer cube root below some number max, then you could:

    max = 12000
    cube_root = int(max ** (1.0/3.0))  # Take cube root and round to nearest integer
    cubed = cube_root ** 3             # Find cube of this number
    print str(cube_root) + " is the cube root of " + str(cubed)  # Output result
    

    The only sticking point for the above is if it happens to start the code with a max that is a cube root, and the cube root rounds to 4.9999999999999. When converted to an integer, this will round to 4, skipping the correct cube root (5) and going straight to "4 is the cube root of 64". You can get around this a few different ways. One way would be to convert the second line to:

    cube_root = int(max ** (1.0/3.0) + 0.5)
    

    This converts the "round down" operation of int() into a "round to nearest" operation.

提交回复
热议问题