Last Updated:

Calculating the Root in Python

In order to extract the root, python has the following methods:

  1. Use the pow function.
  2. Use the sqrt function.
  3. Use the "**" operation.

The pow function allows you to calculate the root by exponentiation to a fractional power. Pow has 2 arguments. The first is the number from which you want to extract the root, and the second is the degree to which you want to raise it.

To calculate the root using this function, you need to use the mathematical rule that the root of the nth degree of the number is equal to this number, raised to the power of "1/n".

An example of finding a root using pow:

print ("Root: ", pow(16, 0.25))// 0.25 = 1/4, so we calculate the root of the 4th degree out of 16

Inference:

Root: 2.0

Using the sqrt function from the math standard library, we can only find the root of the second degree from the number.

from math import sqrt
print («Root: «, sqrt(25))

Inference:

Root: 5.0

Using the "**" operation, as with the pow operation, you can calculate the root of any degree.

print («Root: «, 27**(1/3))

Inference:

Root: 3.0

Square root from a negative number

 

In order to extract the square root from a number that is less than zero, you can use any of the three functions listed above. But it is better to use the sqrt function from the cmath module to avoid errors in calculations.

An example of a program for extracting a root from a negative number:

from cmath import sqrt

print («Root1: «, pow(-7, 1/2))
print («Root2: «, sqrt(-7))
print («Root3: «, (-7)**(1/2))

Inference:

Root1: (1.6200554372175822e-16+2.6457513110645907j)
Root2: 2.6457513110645907j
Root3: (1.6200554372175822e-16+2.6457513110645907j)

Calculating a fractional root

To calculate the root of the fractional degree, you can use both the pow function and the "**" operation. An example of finding a root of fractional degree:

print («Root1: «, pow(3, 1/0.25))
print («Root2: «, 3**(1/0.25))

Inference:

Root1: 81.0

Root2: 81.0