mardi 2 novembre 2021

C - Random value +/- from previous value

I was trying to write some code in C to simulate temperature fluctuations +/- 4 from the previous value, however I'm getting some wild jumps in either direction.

The program is multi-threaded, however, even testing in isolation produces the same wrong results.

I've tried several variations on the code, thinking that it had to do with how the code was evaluating, but my errors but they all end up the same. My code is as follows:

int main(){
    srand(1); //Just for testing and predictability of outcome
    //short int temp = 20 + rand() / (RAND_MAX / 30 - 20 + 1) + 1; Initially I was initialising it at a random value between 20-30, but chose 20 for testing purposes
    short int temp = 20;
    short int new_temp, last_temp, new_min, new_max;
    last_temp = temp;
    for(int i = 0; i < 20; i++){
        //last_temp = temp; At first I believed it was because last_temp wasn't being reassigned, however, this doesn't impact the end result
        new_min = last_temp - 4;
        new_max = last_temp + 4;
        //new_temp = (last_temp-4) + rand() / (RAND_MAX / + (last_temp + 4) - (last_temp - 4) + 1) + 1; I Also thought this broke because they last_temp was being changed with the prior math in the equations. Still no impact
        new_temp = new_min + rand() / (RAND_MAX / + new_max - new_min + 1) + 1;

        printf("Temperature is %d\n", new_temp);
    }
    
    return 0;
}

Produces results like this.

Temperature is 37
Temperature is 26
Temperature is 35
Temperature is 36
Temperature is 38

As you can see, the first temperature reading should be within the range of 16-24, however it increases by 17 to 37, and I can't figure out why. Any insight would be appreciated. In the alternative, can anyone provide me with a clean way to simulate a random +/- without having to use a lot of embedded if statements?




Aucun commentaire:

Enregistrer un commentaire