MATLAB: Isn’t the plot of “sin” a periodic plot of a sine function

accuracyarithmeticdoublefloatingMATLABplotplottingpointprecisionsinsine

Why does this code to plot a sine function not produce a periodic plot of a sine function, as expected?
>> f = 1000;
>> t = 0:0.01:10;
>> y = sin(2*pi*f*t);
>> plot(t,y);

Best Answer

This issue stems from the way in which numbers are represented in MATLAB (using double-precision floating point numbers) in conjunction with choice of "t" and "f" in the code.
To fix this issue, the solution is to use a smaller time step when initializing the time vector "t". That is, choose a smaller value for "dt" when creating the "t" vector as below:
>> t = t_start : dt : t_end;
In general, the larger the frequency "f" is, the smaller the time step "dt" is needed. For example, in this case, with a frequency of 1 kHz, you might use
>> t = 0 : 1e-6 : 0.01;
Note that we also changed the end time, "t_end". This also helps to better visualize the sine function, since for a frequency of 1000 Hz the sine wave originally plotted will go through (t_end-t_start)*f = 10*1000 = 10000 cycles over the time range 0-10. Changing the end time to 0.01 will only plot 10 cycles, making the periodic nature visible.
Below is further information about why this issue is occurring, which may be useful when making changes to the code or for future computations and plotting in MATLAB:
The time vector, "t", and frequency, "f", are chosen such that their product, "f*t", consists of whole number values. Therefore, the argument of the sine function, "2*pi*f*t", consists of whole number multiples of 2*pi. Since the sine of any multiple of 2*pi evaluates to zero, we expect the output of "sin(2*pi*f*t)" to be zero for all values of "t" provided. However, the argument "2*pi*f*t" is an irrational number and can only be represented approximately with floating-point numbers, therefore when MATLAB evaluates "sin(2*pi*f*t)", it gives a number very close to zero, instead of exactly zero. If you observe the resulting plot from the code, you will see this behavior represented by the fact that the values on the y-axis are very close to zero.
For more about accuracy of floating-point numbers, please refer to the following article: