Given
a rectangle with sides of length a and b, where a > b, the ratio of
its sides is a/b. If you join a square to it with sides of length a to
create a new rectangle, the ratio of its sides will be (a+b)/a. If a/b =
(a+b)/a, this is known as the golden ratio. Here is a picture,
which I copied from Wikipedia, to illustrate the concept:
The
program below starts off with 1.5 as an approximation to the golden
ratio then uses iteration to get as close as possible to the true value:
Java > cat golden_ratio.java
public class golden_ratio
{
public static void main (String args[])
{
double ratio1;
double ratio2;
double ratio3 = 1.5d;
double difference;
double percentage_difference;
int iterations = 0;
do
{
ratio1 = ratio3;
ratio2 = 1 / (ratio1 - 1);
ratio3 = (ratio1 + ratio2) / 2d;
difference = Math.abs (ratio3 - ratio1);
percentage_difference = difference / ratio3 * 100d;
iterations++;
}
while (percentage_difference > 0.0000000000001d);
System.out.println ("Golden ratio is " + ratio3);
System.out.println ("Iterations = " + iterations);
}
}
Java > javac golden_ratio.java
Java > java golden_ratio
Golden ratio is 1.6180339887498956
Iterations = 155
Java >