Wednesday 22 June 2011

Heron of Alexandria/Babylonian Algorithm to find square roots

imperative programming :
'imperative programs define sequences of commands for the computer to perform.'

Heron of Alexandria/Babylonian Algorithm to find the square root of a number, 3 versions here:

/*
1. Start with an initial guess (g) of what the square root of some number
(call it n) might be. The initial guess doesn't even have to be close. For simplicity's sake, let's always choose g = 1.
2. Compute result = ((n/g) + g)/2. Let g be the result just computed.
3. Repeat step 2 until the last two results obtained are the same.
sucessive approximation? Adapted from some C++ code I found on the web
*/

void setup() {
}
void draw() {

//doesn't really need to be in draw()

heronSqrt(44);
}

double heronSqrt(int number) {

double x = number/2;
for (int i = 0; i< 10; i++) {
x = (x + number/x)*0.5; //0.5
println("next approximate: " +x);
}
println("Processing guess: " + sqrt(number));
return x;
}
}

////another 2 variants:

//heron 2
void setup() {
heronTwo(44);
println(" ");
println(heron3(44));
}


double heronTwo(int n) {


double guess = n/2;
double r = 0.00;
for(int i = 0; i < 10; i++)
{
r = n / guess;
guess = (guess + r) / 2;
System.out.println(guess);
}

System.out.println("The square root of "+n+" is:");
System.out.printf(" [ %4.2f ]", r);//printf = formatted according to flags

return r;
}


double heron3(double number)

{ //square root Babylonian method



double estimate=number;

double divisor=2;

//below 100 is arbitrary, for very small decimals i values must be large

for(int i=0; i<100; i++)

{

estimate=number/divisor;

estimate=(estimate+divisor)/2; //find average estimate & divisor

divisor=estimate;
}

return estimate;
}

No comments:

Post a Comment