11

I've tried to find the cube root in Python but I have no idea how to find it. There was 1 line of code that worked but he wouldn't give me the full number. Example:

math.pow(64, 1/3)

This doesn't give me 4 tough but 3.99999. Does anyone know how I am supposed to fix this?

A. Johnson
  • 111
  • 1
  • 1
  • 3
  • 1
    Possible duplicate of [Is cube root integer?](https://stackoverflow.com/questions/23621833/is-cube-root-integer) – Aziz Mar 21 '18 at 08:36
  • Possible duplicate of [Is there a short-hand for nth root of x in Python](https://stackoverflow.com/questions/19255120/is-there-a-short-hand-for-nth-root-of-x-in-python) – Pynchia Mar 21 '18 at 08:39
  • `round(math.pow(64,1/3))` is a quick fix – alexod Mar 21 '18 at 08:43

3 Answers3

13

You can use the power operator ** with fractions like:

Python3:

>>> 8**(1/3)
2.0

Python2:

>>> 8**(1.0/3)
2.0
Szabolcs
  • 3,990
  • 18
  • 38
7

This is one option without using math library

>>> 64**(1/3)
3.9999999999999996
>>> round(64**(1/3.),2)
4.0

If you want to do with your code, you can apply 'round()' method

>>>import math
>>>round(math.pow(64,1/3.))
4
Julio CamPlaz
  • 857
  • 8
  • 18
7

in Python 3.11, math.cbrt

 x = 64
 math.cbrt(x)

(or)

use numpy

import numpy as np
x = 64
np.cbrt(x)
SuperNova
  • 25,512
  • 7
  • 93
  • 64