The Python math.sqrt() method is used retrieve the square root of the given value. The square root of a number is the factor of multiplying the number by itself to get that number. Finding the square root of a number is the opposite of squaring a number.
For instance, the number 5 and -5 are square roots of 25, because 52= (-5)2 = 25.
Note − This function is not accessible directly, so we need to import math module and then we need to call this function using math static object.
SyntaxFollowing is the syntax of Python math.sqrt() method −
math.sqrt(x)Parameters
x − This is any number greater than or equal to 0.
This method returns the square root of the given number.
ExampleThe following example shows the usage of the Python math.sqrt() method. Here, we are trying to pass different positive values and find their square root using this method.
# This will import math module import math print "math.sqrt(100) : ", math.sqrt(100) print "math.sqrt(7) : ", math.sqrt(7) print "math.sqrt(math.pi) : ", math.sqrt(math.pi)
When we run above program, it produces following result −
math.sqrt(100) : 10.0 math.sqrt(7) : 2.64575131106 math.sqrt(math.pi) : 1.77245385091Example
If we pass a number less than zero to the sqrt() method, it returns a ValueError.
Here we are creating an object 'num' with the value '-1'. Then we are passing this num as an argument to the method.
# importing the module import math num = -1 # taking a number less than zero res = math.sqrt(num) # printing the result print('The square root of negative number is:',res)
While executing the above code we get the following output −
Traceback (most recent call last): File "C:\Users\Lenovo\Desktop\untitled.py", line 5, in <module> res = math.sqrt(-1) ValueError: math domain errorExample
In here, we are passing 0 as an argument to the sqrt() method. It retrieves the value 0.0 as the result.
# importing the module import math num = 0 # taking a number less than zero res = math.sqrt(num) # printing the result print('The square root of zero is:',res)
Following is an output of the above code −
The square root of zero is: 0.0Example
If we pass a complex number to the sqrt() method, it returns a TypeError.
Here we are creating an object 'x' with the value '6 + 4j'. Then we are passing this num as an argument to the method.
# importing the module import math x = 6 + 4j res = math.sqrt(x) print( "The square root of a complex number is:", res)
Output of the above code is as follows −
Traceback (most recent call last): File "C:\Users\Lenovo\Desktop\untitled.py", line 4, in <module> res = math.sqrt(x) TypeError: must be real number, not complex
python_maths.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4