Protoman wrote:
I'm trying to do this as academic exercise; could you tell me how to
implement the divide and average method in code? Thanks for the help!!!
What about starting with square roots?
Here the idea is that you generate a sequence x_1, x_2, x_3, ... of
approximations that become better and better. The formula is:
x_1 = A
x_{i+1} = 1/2 ( x_i + A / x_i );
A first draft of some experimental code would thus look like this:
#include <iostream>
#include <boost/lexical_cast.hpp>
double recurse ( double x, double A ) {
return( 0.5 * ( x + A/x ) );
}
int main ( unsigned argn, char * args[] ) {
if ( argn >= 1 ) {
double A = boost::lexical_cast< double >( args[1] );
double x = A;
for ( unsigned i = 0; i < 20; ++i ) {
std::cout << x << '\n';
x = recurse( x, A );
}
}
}
Now, there are some problems for you to solve:
a) write a function
double square_root( double A ) {
...
}
based on this idea.
b) In this function, you need to decide how many iterations you want. In the
sample code, I just hardcoded 20. But that is stupid: if you play around
with different values, you will find that sometimes the routine converges
faster and sometimes it takes longer. So, you might want to come up with a
dynamic criterion for when to stop.
Once you understand the square root thing, the n-th root stuff will be a lot
easier.
Hope this helps
Kai-Uwe Bux