Search code examples
pythonmathpython-3.xnth-root

The fourth root of (12) or any other number in Python 3


I'm trying to make a simple code for power 12 to 4(12 ** 4) . I have the output num (20736) but when I want to figure returns (20736) to its original value (12). I don't know how to do that in Python .. in Real mathematics I do that by the math phrase {12؇}

The question is how to make {12؇} in Python ?? I'm using sqrt() but sqrt only for power 2

  #!/usr/bin/env python3.3
import math 
def pwo():
   f=12 ** 4 #f =20736 #
   c=        # should  c = 12 #
   return f,c
print pwo()

Solution

  • For scientific purposes (where you need a high level of precision), you can use numpy:

    >>> def root(n, r=4):
    ...     from numpy import roots
    ...     return roots([1]+[0]*(r-1)+[-n])
    ...
    >>> print(root(12))
    [ -1.86120972e+00+0.j          -3.05311332e-16+1.86120972j
      -3.05311332e-16-1.86120972j   1.86120972e+00+0.j        ]
    >>>
    

    The output may look strange, but it can be used just as you would use a list. Furthermore, the above function will allow you to find any root of any number (I put the default for r equal to 4 since you asked for the fourth root specifically). Finally, numpy is a good choice because it will return the complex numbers that will also satisfy your equations.