2

I want to get a periodic value that moves between 0 and a specified height (in my case that's 40) from the sine curve.

But I am messing something up, because my value goes all the way to 79 instead of the expected 40. What am I doing wrong?

This is my attempt:

#include <math.h>

    #define degToRad(angleInDegrees) ((angleInDegrees)*M_PI / 180.0)
    
    int main()
    {  
        int height = 40;
        int i = 0;
        while (1) {
    
            int value = height + sin(degToRad(i / 2 + 1)) * height;
            printf("val = %i\n", value);
            i++;
        }
        return 0;
    }
Acorn
  • 24,970
  • 5
  • 40
  • 69
Kyu96
  • 1,159
  • 2
  • 17
  • 35
  • 2
    are you sure you do not want to divide by 2.0 rather than by 2 ? `i / 2` is an integer division – bruno Aug 15 '20 at 19:54
  • 4
    The sine function fluctuates between −1 and +1. So `height + sin(something) * height` varies between height + −1•height (which is 0) and height + +1•height (which is 2•height). To make the range go from 0 to height, use `(height + sin(something) * height)/2`. – Eric Postpischil Aug 15 '20 at 19:54
  • what about to also stop the loop when *i* reach a given value ? – bruno Aug 15 '20 at 19:56

2 Answers2

2

The amplitude of the curve would then be height / 2 and not height; simply replace

int value = height + sin(degToRad(i / 2 + 1)) * height;

with

int value = height / 2 + sin(degToRad(i / 2 + 1)) * height / 2;

A good way to remember that is that sin x is always in the range [-1, 1].

Hi - I love SO
  • 615
  • 3
  • 14
2

A direct resolution is to divide the wave magnitude by 2 @Eric Postpischil

// int value = height + sin(degToRad(i / 2 + 1)) * height; 
int value = height + sin(degToRad(i / 2 + 1)) * height)/2;

and use floating point math in the i/2 division. @bruno


I expect a more acceptable result using rounding rather than truncation (what OP's code does) going from floating point to int.

int value = height + lround(sin(degToRad(i / 2 + 1)) * height)/2);
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256