Can you code this for me? (short problem)

Im trying to figure out how to code this problem and i have no idea how it looks. Can someone please look at it for me? Here it is:

Implement a sqrt function based on the following idea: we bound the square root of x from the left and the right. Initially, the square root of x must satisfy:

0 ≤√x ≤ max(x,1)

So if we initially let a = 0 and b = max(x,1), then the square root of x is in the interval [a,b]. To assign b, an if statement can compare x to 1. Now let m be the middle point of the interval [a,b] (we can use the average function to find it). While m 2 is not close enough to x we repeatedly perform the following (otherwise, we return m):
• if m 2 ≤ x, we assign a the value of m, i.e. the interval becomes [m,b]
• if m 2 ≥ x, we assign b the value of m, i.e. the interval becomes [a,m]
• update m to be the middle of the interval [a,b]


Huge thank you in advance.
Sounds and looks a lot like binary search:

http://en.wikipedia.org/wiki/Binary_search_algorithm

I'm guessing that by m 2, you mean m2?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <algorithm> // std::max
double binary_sqrt(double num)
{
	double a(0), b = std::max(num, 1.0), m = (a + b) / 2;
	while (m * m not close to num)
	{
		double prod = m * m;
		if (prod <= num)
			// ???
		else if (prod > num)
			// ???
		m = // ???
	}
	return m;
}
Last edited on
Topic archived. No new replies allowed.