3
\$\begingroup\$

I have a basic understanding of sine wave generation. The problem I am facing is that as the input parameter for time gets larger, my sine wave falls apart and starts to look really ugly.

I'd like to calculate a sine wave without depending on an ever increasing time value. How can I do this?

\$\endgroup\$
9
\$\begingroup\$

You could restart your time value every 2pi:

if(time > 2*pi)
  time -= 2*pi;

If is still okay to increase your time variable infinitely but the input for the sine is to large, just use fmod(time, 2*pi).

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ thank you, using fmod worked. It seemed to keep the values between 2*pi. Quick question, what does fmod do? I read this: tutorialspoint.com/c_standard_library/c_function_fmod.htm it says fmod returns the remainder but I don't get why it works. \$\endgroup\$ – tmp Sep 5 '15 at 17:27
  • 1
    \$\begingroup\$ basically it returns r in the equation x = n*y + r where x and y are the inputs and n is an integer. \$\endgroup\$ – ratchet freak Sep 5 '15 at 18:25
  • \$\begingroup\$ The reason you hit the issue you did is that as floating point numbers get larger, they lose accuracy. For instance if you start at zero and add one to a floating point number in an infinite loop, there will come a point where adding the 1 results in the same value (ie will have no effect) \$\endgroup\$ – Alan Wolfe Sep 6 '15 at 0:52
  • \$\begingroup\$ @ratchetfreak so is fmod like the modulus operation? \$\endgroup\$ – tmp Sep 6 '15 at 15:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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