The Golden Ratio

Like many other mathematical delights, the golden ratio pops up all over. It has a rich history, and a special Greek letter to represent it: φ phi. The value is irrational, meaning it cannot be expressed as a ratio of two integers: 1.6180339…

What this ratio represents is illustrated in Figure 1. The length of a+b is the same ratio to a as length b is to length a. This concept is difficult to put into words, which is why I animated the figure.

Golden ratio animation showing a+b/a

Figure 1. An animation showing the relationship between ‘a’ and ‘b’ relative to each other.

The expression to describe the relationship between lengths a and b is written like this:

(a+b)/a == a/b == φ

Mathematicians using brains far more massive than my own have determined, by using the quadratic formula and other scary words, that this equation works out like this:

(1+√5)/2 = 1.6180339887…

Unlike π, e, √2, and other values, the golden ratio doesn’t exist as a defined constant in the math.h header file. If your code demands it, you must perform some math, as shown in the following example:

2020_11_14-Lesson.c

#include <stdio.h>
#include <math.h>

int main()
{
    double gr;

    gr = (1.0 + sqrt(5)) / 2.0;
    printf("The golden ratio is %f\n",gr);

    return(0);
}

The math.h header file is required for the sqrt() function, used in the equation at Line 8. This expression matches the one used to determine the value of φ, as shown earlier. And remember, some systems require that you link in the math library (m) for the sqrt() function to behave properly.

Here is the output:

The golden ratio is 1.618034

A second way exists to calculate the golden ratio. This method using a continued fraction, which is one of those terrifying constructions illustrated in Figure 2.

phi expressed as a continued fraction, which really looks scary

Figure 1. Calculating φ as a continued fraction – something that begs for a recursive function.

When I see a mathematical goober such as the one shown in Figure 2, as a programmer I see a recursive function. I explore this option for calculating the golden ratio in next week’s Lesson.

Leave a Reply