Created
February 18, 2010 17:04
-
-
Save jvoorhis/307843 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Bandlimited interpolation simulation, as described by Eq 1 of | |
# https://ccrma.stanford.edu/~jos/resample/Theory_Ideal_Bandlimited_Interpolation.html | |
Fs = 44100.0 # sampling rate | |
Ts = 2.26757369614512e-05 # sampling interval (1/Fs) | |
def interp(samps, t) | |
(0...samps.size).inject(0) { |sum, n| | |
sum + samps[n] * hs(t - n * Ts) | |
} | |
end | |
def hs(t) | |
sinc(Fs * t) | |
end | |
def sinc(t) | |
if t.zero? then 1.0 | |
else | |
Math.sin(Math::PI * t) / (Math::PI * t) | |
end | |
end | |
# A continuous-time 440 Hz sine wave | |
def x(t) | |
Math.sin(2.0 * Math::PI * 440.0 * t) | |
end | |
# Sample 1sec of a continuous function | |
def samp | |
Array.new(Fs) { |n| yield(n*Ts) } | |
end | |
# 440 Hz sine wave sampled at 44.1 kHz | |
sine = samp { |t| x(t) } | |
# Randomly sample continuous function and its reconstruction from a discrete signal | |
puts "T\t\tx(T)\t\tinterp(samp(x), T)\tdelta" | |
1000.times do | |
t = rand() | |
xt = x(t) | |
it = interp(sine, t) | |
puts "% .4fsec\t% .4e\t% .4e\t\t%.4e" % [t, xt, it, (xt-it).abs] | |
end | |
# Compare sampled sine wave with reconstruction at sampling points | |
(0...Fs).each do |n| | |
puts "%.7f\t%.7f" % [x(n/Fs), interp(sine, n/Fs)] | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment