Where do the frequencies of musical notes come from? Why are piano keys and guitar frets placed where they are?
The answer is a mathematical system called 12-Tone Equal Temperament.
To understand it, we start with three fundamental principles:
The Octave: When you double a sound's frequency ($2 \times f$), the human ear hears the two tones as the exact same note class, just higher in register. For example, A3 is $220\text{ Hz}$, A4 is $440\text{ Hz}$, and A5 is $880\text{ Hz}$.
12 Semitones: In Western music, the span of one octave is split into $12$ steps called semitones (or half-steps):
$$\text{C, C}\sharp\text{, D, D}\sharp\text{, E, F, F}\sharp\text{, G, G}\sharp\text{, A, A}\sharp\text{, B, C}$$
Equal Temperament: To allow musicians to play in any musical key without sounding out of tune, the frequency ratio $r$ between every pair of adjacent semitones must be identical. Since multiplying by $r$ twelve times in a row must double the frequency ($r^{12} = 2$), the ratio must be the twelfth root of two:
$$r = 2^{1/12} = \sqrt[12]{2} \approx 1.059463094$$
Taking international standard concert pitch A4 ($440\text{ Hz}$) as our benchmark, the frequency of any note $n$ semitones away is given by the exponential formula:
$$f(n) = 440 \cdot 2^{n/12}$$
Using Lua's exponentiation operator ^ along with sound(freq, duration) and play(), you can program any musical scale or melody purely from mathematical laws!
for n = 0, 12 do freq = 440 * (2 ^ (n / 12)) sound(freq, 0.25) end play()
Move the mouse over a dotted box for more information.
The Major Scale ("Do Re Mi Fa Sol La Ti Do"): A major scale is created by selecting 7 notes out of the 12 chromatic semitones using the interval pattern: Whole, Whole, Half, Whole, Whole, Whole, Half. That corresponds to semitone offsets:
$$[0, 2, 4, 5, 7, 9, 11, 12]$$
Why Guitar Frets Get Closer: On a stringed instrument, frequency is inversely proportional to vibrating length ($L \propto 1/f$). Each fret shortens the string by a factor of $2^{-1/12} \approx 0.9439$. Because this reduction is geometric, the frets get progressively closer together as you move down the neck!
Now you try. Replace ???? with 12 to complete the scale. Then try changing the offsets to {0, 2, 3, 5, 7, 8, 10, 12} to hear a natural minor scale!
Type your code here:
See your results here:
The default code calculates and plays the iconic C Major Scale ("Do Re Mi Fa Sol La Ti Do") using equal temperament mathematics!
Replace ???? with 12 (the final octave note).
When you click Run, notice how the computer prints each note's exact frequency (C: 261.63 Hz, D: 293.66 Hz, E: 329.63 Hz...) and plays the melody through your speakers!
Share your code
Show a friend, family member, or teacher what you've done!