When we convert to digital we have to fit to the digitization level, which causes a quantization error:
Quantization |
Source code
The following outlines the Python code used:
import matplotlib.pyplot as plot import numpy as np import sys from scipy import signal import math file ='1111' bits=4 type='sin' freq=5 if (len(sys.argv)>1): file=str(sys.argv[1]) if (len(sys.argv)>2): noise=float(sys.argv[2]) if (len(sys.argv)>3): type=(sys.argv[3]) if (len(sys.argv)>4): freq=int(sys.argv[4]) def quant(bits,val,min,max): levels=2**bits error=1000 level=min step=(max-min)/(2**bits) for x in range(0,levels+1): newerror = math.fabs(val-level) if (newerror<error): nearest = level error = newerror level = level + step return nearest Fs = 100.0; # sampling rate Ts = 1.0/Fs; # sampling interval t = np.arange(0,0.5,Ts) if (type=='sin'): y= np.sin(2 * np.pi * freq * t) elif (type=='square'): y= signal.square(2 * np.pi * freq * t) elif (type=='triangle'): y= signal.sawtooth(2 * np.pi * freq * t,width=0.5) elif (type=='gausspulse'): y= signal.gausspulse(t,fc=freq,bw=0.5,bwr=-6,retquad=0) elif (type=='chirp'): y= signal.chirp(t, f0=0, t1=1, f1=freq, method='linear', phi=0) else: y= signal.sawtooth(2 * np.pi * freq * t) val = [] for i in range(0,len(t)): val.append(quant(bits,y[i],-1.0,1.0)) print (val[i]) fig,myplot = plot.subplots(2, 1) myplot[0].plot(t,y) myplot[0].set_xlabel('Time') myplot[0].set_ylabel('Amplitude') myplot[1].bar(t,val,width=Ts) myplot[1].set_xlabel('Time') myplot[1].set_ylabel('Amplitude') plot.savefig(file) plot.show() print ("Saving to",file)