Problem Statement: Find square root of any number in Python with and without using inbuilt functions.
Description: Python is one of the best languages that is gaining popularity day by day. It has inbuilt libraries to do most of the complex work behind the scenes.
However, there are situations when we cannot use the internal library of the language (for example in a job interview). There are many ways to find the square root of a number in python, with and without using internal libraries.
How to find the square root of a number in python?
Here are the three most common ways to find square root in Python.
This is the easiest method to find square root in Python.
import math num = int(input("Number to find Square root: ")) sqroot = math.sqrt(num) print(sqroot)
Number to find Square root: 25 5.0
This is the most common method if you are working on a project that needs many complex mathematical operations. We import Math module and find the square root of a number in python using that.
We can write the above code in a more pythonic way.
import math print(math.sqrt(int(input("Number to find Square root "))))
Using Exponential Operator
num = int(input("Number to find Square root ")) sqroot = num**0.5 print(sqroot)
There is a little bit of math going here (it’s not scary).
If you square the number it gets the exponent of two, so if you want to square root of number then give it exponent of 0.5. This is done with respect with ideal number one.
4^1 = 4
4^2 = 16 (square of number as power 2)
4^0.5 = 2
16^0.5 = 4 (square root of number)
Here we can see that if the exponent is 1 then it gives the original number (now take 1 as origin), power 2 gives the square of that number (2 is twice of 1 which is the origin of our assumption), 0.5 which is half of 1 gives the square root of that number. Hope that makes sense.
Find square root Using
Math.pow of Python
import math num = int(input("Number to find Square root ")) sqroot = math.pow(num, 0.5) print(sqroot)
To find the square root of a number in python this method uses the same logic as the exponent of 0.5 but instead on exponent operator, it uses the pow method of Math module.
The pow method takes two arguments, the first one is the number and the second argument is the power to which it is raised or exponent is calculated.
It returns the value after performing the exponent operation internally.
These were some of the widely used ways to find square root in python. If you faced any problem with the code let me know in the comments.
You may also like: