In this type of problem, where you're naturally looking at physical quantities, it's very helpful to be consistent with this all the way through your calculations.
Specifically, you specify Hz (1/seconds), a physical unit, so when you calculate everything else, you need to be consistent with that.
To do this in your equation, it's most straightforward to put time directly in the sin
function, like sin(2*pi*f*t)
. But since you want to break the array apart using different n
, it probably easiest to do that and then use t=linspace(0,5,50000)
and dt = 5.0/50000
or dt = t(2) - t(1)
, and sin(2*pi*400*dt*n1)
. Read this as dt*n1
converts the integers in n1
to time in seconds.
Note the physical units too: 400
in above is actually 400Hz
, and the time is in seconds, so the units of 2*pi*400*dt*n1
and 2*pi*f*t
are Hz * s = 1
, that is, the units cancel, which is what you need.
There is a tendency for programmers to want to define away some unit, like say seconds=1
. This is possible and technically correct and can save a multiplication or two. It almost always leads to errors.
Note also that you should change from t=linspace(0,5,5000)
to something like t=linspace(0,5,50000)
. The reason should now be clear: you're looking at frequencies from 400-800Hz, or almost 1kHz
, or 1 oscillation per millisecond. To see a sine wave, you'll need to get in a few data points per oscillation, and 50000
points in 5 seconds will now give about 10 points per millisecond, which is barely enough to see a reasonable sine wave. Or, however you want to think of the calculation, somehow you need to be sure you sample at a high enough rate.
That is, the specific error that your encountering is that by using integers instead of fractions of a second for your time array, you're taking much too large of steps for the sin
function. That's always a possible problems with the sin
function, but even if you did plot a sin
that looked like a sin
(say, by using a frequency like 0.003Hz instead of 400Hz) it would still be incorrect because it wouldn't have the proper time axis. So you need to both get the units correct, and make sure that you get enough data per oscillation to see the sine wave (or whatever it is you happen to be looking for).
t(n1+1)
notn1
, you want time in the equation, not indices), but you are simulating 5 seconds. That is 4000 periods of 800Hz. You can not sample that signal with 5000 samples (linspace). Read what Nyquist frequency is and what it says about sampling singnals - Ander Biguri