Skip to content

Instantly share code, notes, and snippets.

@tsbertalan
Created November 25, 2012 06:35
Show Gist options
  • Save tsbertalan/4142645 to your computer and use it in GitHub Desktop.
Save tsbertalan/4142645 to your computer and use it in GitHub Desktop.
Graphical demonstration of beat frequency as heard when tuning a violin
# Really, when tuning, you have a reference note a fifth above or below the
# target note. But, just to show a beat-frequency effect, having the reference
# and target notes be about the same frequency is fine.
import numpy as np
import matplotlib.pylab as plt
length = 444 # make this larger if the waves shown are not very wave-like
resolution = 10000.0
xl = list(np.arange(1, length, length / resolution))
w1 = 1.0
randomlevel = 1 # use this to make the depiction seem a little more realistic
randomness = lambda : np.random.rand() * randomlevel
wave1 = [np.sin(w1 * x) + randomness() for x in xl]
delta = 0.04 # make this smaller to show the effect of more accurate tuning
w2 = w1 + delta
wave2 = [np.sin(w2 * x) + randomness() for x in xl]
wave12 = [x + y for (x, y) in zip(wave1, wave2)]
# comment/uncomment any of the following three lines to hide/show plots
fig = plt.figure()
ax1 = fig.add_subplot(2,1,1)
ax2 = fig.add_subplot(2,1,2)
fig.suptitle('Beat Frequency Demo')
ax1.plot(xl, wave1) # the reference note
ax1.plot(xl, wave2) # the target note for tuning
ax2.plot(xl, wave12) # the audible 'note', including a beat-frequency pattern
ax1.legend(['reference note', 'target note'])
ax2.legend(['audible superposition'])
fig.savefig('beat.png')
#plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment