Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is the square root function implemented? [closed]

How is the square root function implemented?

like image 613
pp7 Avatar asked Aug 27 '10 05:08

pp7


People also ask

How is square root 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.

How is square root implemented in Python?

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).

How does square root function work?

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.

How is C++ sqrt implemented?

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.


1 Answers

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

like image 190
Amr Saber Avatar answered Sep 21 '22 21:09

Amr Saber