1
$\begingroup$

I am trying to create a sine wave in python, but when I graph it, it looks like this:

enter image description here

here is the code I used to make the signal:

c_freq = 1700 * 1000
fs = c_freq * 2
secs = 3
x = fs*secs

t = np.linspace(0, secs, x)
carrier = np.sin(t * c_freq * 2 * np.pi)

Why is the amplitude changing throughout the signal and how can I fix this?

$\endgroup$
4
  • 3
    $\begingroup$ We've had fun with this one. $\endgroup$ Jun 16, 2021 at 4:40
  • $\begingroup$ I'm sorry, I'm not sure I get it. What should I do to fix this problem? $\endgroup$
    – user57935
    Jun 16, 2021 at 5:01
  • 2
    $\begingroup$ increase your sampling rate. $\endgroup$ Jun 16, 2021 at 5:16
  • $\begingroup$ Why is it a problem? The graph looks funny but everything you do with the data will stay work. Is this a cosmetic or technical issue ? $\endgroup$
    – Hilmar
    Jun 16, 2021 at 11:51

1 Answer 1

3
$\begingroup$

Why is the amplitude changing throughout the signal

Because you are sampling it at oh so slightly less than c_freq/2. Your linspace call generates x points that are evenly spaced between 0 and 3, with a spacing between them of 3 * c_freq * 2 / (3 * c_freq * 2 + 1). This means that the phase that gets calculated is $\begin{bmatrix}0, \pi-\epsilon, 2\pi - 2\epsilon,\cdots,(n-1)\pi-\pi+\epsilon, n \pi - \pi\end{bmatrix}$ -- and that gives the result you see, with alternating numbers on a half-rotation envelope.

(Why does it do that? Work it out -- it'll be good for you. Start by looking at how linspace actually behaves, i.e. linspace(0, 10, 10)).

and how can I fix this?

What's wrong with it? What do you want? If you want a pretty sine wave, you need to sample way more than twice the frequency, and everyone defines "pretty" differently, so there's no fixed number. I usually use 100 points per cycle of a sine wave -- but that would get pretty time intensive given that you want to plot three seconds of a 1.7MHz sine wave.

$\endgroup$
1
  • $\begingroup$ linspace(a,b,N) has a spacing of (b-a)/(N-1), there is one less segment than the number of nodes. $\endgroup$ Aug 6, 2022 at 12:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.