cmathtrigonometrycurvedegrees

Calculate sine curve in C


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;
    }

Solution

  • 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);