An analogue-to-digital converter (ADC) turns a voltage into a whole number with a fixed number of bits. An ADC with bits bits and input range -vref to vref volts splits that range into 2**bits equal bins of width
q = 2 * vref / 2**bits (the step size, in volts)
Bin c (for c = 0, 1, ..., 2**bits - 1) covers the voltages from -vref + c * q up to, but not including, -vref + (c + 1) * q. For each input voltage v the converter:
- computes
c = floor((v + vref) / q)(usemath.floor), - clamps it: a
cbelow0becomes0, and acabove2**bits - 1becomes2**bits - 1. Such a sample is clipped (this happens exactly whenv < -vreforv >= vref), - reports the code
c. Software that reads the code rebuilds the voltage as the middle of the bin,-vref + (c + 0.5) * q.
The quantisation error of a sample is the distance between v and its rebuilt voltage. Inside the range it is never more than q / 2; a clipped sample can be much further off.
Write quantise(volts, bits, vref) that returns a tuple (codes, max_error, clipped): the list of codes, the largest quantisation error over all samples, and the number of clipped samples.
Examples
Input: volts = [-1.1, -0.3, 0.1, 0.6, 0.9, 1.4], bits = 2, vref = 1
Output: ([0, 1, 2, 3, 3, 3], 0.65, 2)
Explanation: q = 2 / 4 = 0.5, so the bins start at -1, -0.5, 0 and 0.5.
-1.1 V is below the range and 1.4 V above it, so both are clipped. 1.4 V gives code 4,
clamped to 3 and rebuilt as 0.75 V: an error of 0.65.
Input: volts = [0.1, 1.234, -2.0], bits = 8, vref = 2.5
Output: ([133, 191, 25], 0.007421875, 0)
Explanation: 256 bins of q = 5 / 256 = 0.01953125 V; no error is above q / 2.
Constraints
- answers are compared with a tolerance of
1e-6
Goals
- Map a voltage to one of 2**bits whole-number codes with a step size q
- Clamp codes for inputs outside the converter's range and count those clipped samples
- Measure the quantisation error by rebuilding a voltage from each code