Tuning Frequncies
Most recently, I attacked an interesting task: tuning a raw frequency to the nearest note.
First, you have to know a few things about the equal-tempered chromatic scale:
- There are 12 notes in every octave.
- A note that is one octave higher than another note will have twice the frequency.
- So, to move up one chromatic note, you multiply the current note by the twelth root of 2.
Knowing this, we can write this equation:
where:
- f is the raw frequency (this is the input to the function)
- C0 is the frequency of the lowest note, 16.35
- n is the amount of doubling required.
This equation can be solved for n:
Since we know that every time a note doubles the octave increases once, the integer part of n must be equal to the octave.
Since we know there are twelve notes in an octave, we determine which note in the scale the raw frequency represents by multiplying the decimal by 12.
Taking this all into account, I came up with the following method:
Then, I wanted to be sure I made no mistakes, so I found a chart of all the frequencies of the equal-tempered chromatic scale and wrote a few test cases. If you run the following test, you will see that the tuning function works perfectly.