Please use
[CODE][/CODE] tags around your code, so that it is easier to read. For one, it retains the indentation.
First question is: How do you calculate the initial guess?
Usually something like this is done using a very simple function, something like
Code:
double initial_guess(const double value)
{
return value - 1.0;
}
which just returns one less than the value. It is obviously a very bad choice; I just showed that as an example. You might try, for example, halving the original value. I think that would be the simplest good guess. Better guesses exist, but they need a bit more logic, I think.
The
const in the parameter declaration tells your compiler that you will not be changing the value of
value inside your function, so it can be heavily optimized (cached) during calculations. It leads to better code. In any case, function parameters are passed by value; without the const, you can change
value, but those changes are visible only within the function, they're not propagated to the caller.
The second function is a classical case of
iteration. The important parts for such a function for me would be
Code:
double babylonian_square_root(const double value, const double guess, const double maxerror)
{
const double maxsquared = maxerror * maxerror;
double answer = guess;
double error;
if (value <= 0.0)
return 0.0;
do {
/*
* Calculate new answer here
*/
error = value - answer * answer;
} while (error * error > maxsquared);
return answer;
}
Note that this has no iteration limit: if your answer does not eventually arrive at a good enough solution, the loop will run forever.
There is a very practical trick here, too: I am using the square of the error to determine when the result is good enough. Main reason is that square is always positive. (Otherwise you'd have to take the absolute value of the error for comparison.) Another reason is the limited precision of floating-point numbers: squaring helps avoid precision-related issues near zero, because values close to zero will be treated as real zeros.
Instead of having the guess as a parameter, you could also omit it from the function parameter list, then use
answer = initial_guess(value); before the do loop. In that case this latter function would automatically call the first function to obtain the initial guess.