#Does this code accurately simulate the amount of money in 50 years if given 1 random bill per day?

7 messages · Page 1 of 1 (latest)

open aurora
#
#include <Windows.h>
#include <bcrypt.h>
#include <stdio.h>

int gen_rand(){
    unsigned int hold = 0;
    const unsigned int max = 4294967292;

    NTSTATUS nstatus = BCryptGenRandom(
        NULL,
        (unsigned char *)&hold,
        sizeof(hold),
        BCRYPT_USE_SYSTEM_PREFERRED_RNG
    ); //get random number, BCryptGenRandom is much more random than rand()

    if (hold > max){
        return gen_rand(); //prevent modulo bias
    } else {
        hold = hold % 7;
        return hold;
    } //modulo by 7 to get a random value from 0 to 6 (zero is included, so all 7 bills)

}

int main(){
    int count = 10; //do 10 times for an average
    int money1 = 0;
    repeat:

    while (count > 0){
    int x = 0;
    unsigned int money = 0;
    int days = 18263; //50 years, rounded up from 18262.5 (includes leap)
   

    for(days; days > 0; --days){
            x = gen_rand();
            switch (x){
                case 0: money += 1;
                break;
                case 1: money += 2;
                break;
                case 2: money += 5;
                break;
                case 3: money += 10;
                break;
                case 4: money += 20;
                break;
                case 5: money += 50;
                break;
                case 6: money += 100;
                break;
            }
    }
    money1 += money; //add money up to save
    count -= 1;
    goto repeat;
   
 }
 printf("Average for 50 years: %d\n", money1 / 10); //divide money by 10 to account for 10 simulations
 printf("Average per year: %d", money1 / 500); //divide by 10 then 50 (500) for average per year
 return 0;

   
}

Average for 50 years: 491911
Average per year: 9838

Any other tips?

eternal marsh
#

Why do you have a goto?

#

The while loop will handle going back to the top of the loop

#

Assign days in your for loop set up, no need to create the variable in the outer scope.

#

And yes this should accurately accumulate the value of one random bill per day over 50 years

open aurora
#

do you know if there's anything more efficent than a switch statement?