How do you find a square root in Python?


Quick Answer

The simplest method for finding a square root in Python is to use the square root function in the math library. It is called with the operand as a parameter. For example, "math.sqrt(2)" calculates the square root of 2.

Continue Reading

Full Answer

Alternatively, since calculating a square root is equivalent to raising the operand to the power of 0.5, finding a square root can also be achieved by using Python's built-in exponentiation operator, which is a double-asterisk. For example, use "2 ** 0.5" to find the square root of 2.

An exponentiation function that behaves in exactly the same way as the double-asterisk is also built in to Python. To find the square root of 2 with this method, enter "pow(2, 0.5)." In both cases, if both the operand and the exponent are integer numbers, the result is an integer. When calling either the pow function or the double-asterisk operator with mixed data types, the result follows the coercion rules for binary arithmetic operators.

Similarly, it is possible to calculate a square root with exponentiation functions from the math module. For the square root of 2, this method would be entered as "math.pow(2, 0.5)." In contrast to the double-asterisk operator and the built-in pow function, the pow function in the math module converts both of its arguments to floating point numbers before computing the result, which means the result is always a floating point number.

When calculating the square root of a negative number, as in math using complex numbers, use the square root function found in the cmath library. For example, enter "cmath.sqrt(-2)" to find the square root of negative 2.

Learn more about Computer Help

Related Questions