2.18 Global Variables

Contrary to local names that have a limited scope, a global variable is a name that can be seen anywhere in the program. Its context is, therefore, the entire program. The name pi represents the constant \(\pi=3.14159...\) and can be used in any part of our program. For that reason, pi is a global variable.

The definition of global variables is similar to that of local variables, with the difference of being defined outside a function. Therefore, if we wish to introduce a new global variable, for example, the golden ratio:

The golden ratio is also known as gold proportion or divine proportion, among other names. It is abbreviated \(\phi\) in honor of Phidias, the Greek sculptor responsible for the construction of the Parthenon where, supposedly, this proportion was used. The golden ratio was first introduced by Euclid when solving the problem of dividing a line segment into two parts, such that the ratio between the line segment and the longest part was equal to the ratio between the longest part and the shortest part. If \(a\) is the length of the longest part and \(b\) is the length of the shortest part, the Euclid’s problem is equivalent to \(\frac{a+b}{a}=\frac{a}{b}\). As a result, \(a^2-ab-b^2=0\) or \(a=\frac{b\pm\sqrt{b^2+4b^2}}{2}=b\frac{1\pm\sqrt{5}}{2}\). Given that only the positive root makes sense, we have \(a=b\frac{1+\sqrt{5}}{2}\). The expression for calculating the golden ratio is thus: \(\phi=\frac{a}{b}=\frac{1+\sqrt{5}}{2}.\)

\[\phi=\frac{1+\sqrt{5}}{2}\approx 1.6180339887\]

We simply need to write:

golden_ratio = (1+sqrt(5))/2

From this moment on, the golden ratio can be referenced in any part of our program.

It is important to note that global variables should be mostly used to define constants.