Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I root in python (other than square root)? [duplicate]

Tags:

python

math

I'm trying to make a calculator in python, so when you type x (root) y it will give you the x root of y, e.g. 4 (root) 625 = 5.

I'm aware of how to do math.sqrt() but is there a way to do other roots?

like image 963
Josh Avatar asked Oct 28 '25 15:10

Josh


2 Answers

Use pow:

import math

print(math.pow(8, 1/3))

Output

2.0

For your example in particular:

print(math.pow(625, 1/4))

Output

5.0

See more about exponentiation with rational exponents, here. Note that in Python 2, as mentioned by @Jean-FrançoisFabre, you need to specify the exponent to 1.0/n.

like image 65
Dani Mesejo Avatar answered Oct 30 '25 04:10

Dani Mesejo


If you want to 625^(1/4){which is the same as 4th root of 625} then you type 625**(1/4)

** is the operator for exponents in python.

print(625**(1/4))

Output:

5.0

To generalize:

if you want to find the xth root of y, you do:

y**(1/x)

like image 30
involtus Avatar answered Oct 30 '25 04:10

involtus