How is the square root function implemented?
Create a variable (counter) i and take care of some base cases, i.e when the given number is 0 or 1. Run a loop until i*i <= n , where n is the given number. Increment i by 1. The floor of the square root of the number is i – 1.
The most common or easiest way is by using a math module sqrt function. Python sqrt function is inbuilt in a math module, you have to import the math package (module). The sqrt function in the python programming language that returns the square root of any number (number > 0).
The square root function is a one-to-one function that takes a non-negative number as input and returns the square root of that number as output. For example the number 9 gets mapped into the number 3. The square function takes any number (positive or negative) as input and returns the square of that number as output.
Square root in C++ – sqrt() function C++ provides us an inbuilt library function to calculate the square root of any non-negative number. If we pass a negative number as a parameter, then it will result in a domain error. sqrt() function is defined in <cmath> header file.
Simple implementation using Binary Search with C++
double root(double n){ // Max and min are used to take into account numbers less than 1 double lo = min(1, n), hi = max(1, n), mid; // Update the bounds to be off the target by a factor of 10 while(100 * lo * lo < n) lo *= 10; while(0.01 * hi * hi > n) hi *= 0.1; for(int i = 0 ; i < 100 ; i++){ mid = (lo+hi)/2; if(mid*mid == n) return mid; if(mid*mid > n) hi = mid; else lo = mid; } return mid; }
Note that while
loop is most common with the binary search but Personally I prefer using for
when dealing with decimal numbers, it saves some special cases handling and gets pretty accurate result from small loops like that 1000
or even 500
(Both will give the same result for almost all numbers but just to be safe).
Edit: Check out this Wikipedia article for various -special purpose- methods specialized in computing the square root.
Edit 2: Apply updates suggested by @jorgbrown to fix the function in case of input less than 1. Also, apply optimization to make the bounds off the target root by a factor of 10
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With