Calculate sine curve in C

Viewed 204

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

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].

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