Problem 143382 · easy · Level 01 Prerequisites & Setup

Sampling a Tuning Fork

sampling · sample rate · sine wave · loops · math module

A tuning fork rings as a sine wave: at time t seconds its sound pressure is amplitude * sin(2 * pi * freq * t), where freq is the pitch in hertz (cycles per second). A digital recorder does not keep the whole curve. It measures it fs times per second (the sample rate, in hertz), so sample number k is taken at time t = k / fs seconds, for k = 0, 1, 2, ....

Write sample_tone(amplitude, freq, fs, n) that returns a pair:

  1. the list of the first n samples, amplitude * sin(2 * pi * freq * k / fs) for k = 0, 1, ..., n - 1,
  2. the length of the recording in seconds. Each sample stands for 1 / fs seconds of sound, so n samples last n / fs seconds.

Use math.sin and math.pi. Press Run with plot(sample_tone(1, 3, 40, 40)[0], kind="stem") to see one second of a 3 Hz tone, 40 dots per second.

Examples

Input:  amplitude = 2, freq = 1, fs = 4, n = 5
Output: ([0.0, 2.0, 0.0, -2.0, 0.0], 1.25)
Explanation: the samples are taken at t = 0, 0.25, 0.5, 0.75 and 1.0 s: a quarter of a cycle
apart. Five samples of a quarter second each last 1.25 s.

Input:  amplitude = 1, freq = 440, fs = 8000, n = 0
Output: ([], 0.0)

Your values may show tiny rounding noise such as 2.4e-16 where the exact answer is 0; that counts as correct.

Constraints

  • answers are compared with a tolerance of 1e-6; do not round

Goals

  • Turn a sample number k into a time t = k / fs
  • Build a list of samples by evaluating a function at those times
  • Work out how long a recording of n samples lasts
Starting Python…