Digital Sound & Music: Concepts, Applications, & Science, Chapter 5, last updated 6/25/2013
for simplicity, include some C++ features like dynamic allocation with new and the ability to
declare variables anywhere in the program.)
int f = 440;
int r = 44100;
double s = 1;
int b = 8;
double* y = new double[r*s];
for (int t = 0; t r * s; t++)
y[t] = sin(2*PI*f*(t/(r*s)));
To quantize the samples in y to a bit depth of b, we do this:
int sample_max = pow(2, b-1) – 1;
short* y_quantized = new short[r*s];
for (int i = 0; i r * s; i++)
y_quantized[i] = floor(y * sample_max);
The suggested programming exercise linked with this section uses code such as
this to implement Algorithm 5.1 for aliasing and to experiment with
quantization error at various bit depths.
5.3.7 The Mathematics of Dithering and Noise Shaping
Dithering is described in Section 188.8.131.52 as the addition of low-amplitude random noise to an
audio signal as it is being quantized. The purpose of dithering is to prevent neighboring sample
values from quantizing all to the same level, which can cause breaks or choppiness in the sound.
Noise shaping can be performed in conjunction with dithering to raise the noise to a higher
frequency where it is not noticed as much. Now let’s look at the mathematics of dithering and
First, the amount of random noise to be added to each
sample must be determined. A probability density function
can be used for this purpose. We’ll use the triangular
probability density function graphed in Figure 5.39 as an
example. This graph depicts the following:
There is 0 probability that an amount less than 1 and
greater than 1 will be added to any given sample.
As x moves from 1 to 0 and as x moves from 1 to 0,
there is an increasing probability that x will be added
to any given sample.
Thus, it’s most likely that some number close to 0 will be added as dither, and the highest
magnitude value to be added or subtracted is 1. If you were to implement dithering yourself in
MATLAB or a C++ program (as in the exercises associated with this section), you could create a
triangular probability density function by getting a random number between 1 and 0 and
another between 0 and 1 and summing them.
Error in C++
Files in C++