Program that simulates a coin toss with a bias coi

2019-03-05 02:16发布

问题:

I don't have any code, mainly because I haven't started working on this particular problem. It is for homework for my C Programming class.

My professor wants us to create a program that tosses a coin (heads or tails) 10,000 times. However, the heads element has a 55% chance to occur. We have to use a random number generator with a user-supplied seed value.

Conceptually, I know how to approach this; coding-wise, I have no clue. I know how to make a coin tossing program, but not with a bias.

Any and all help would be appreciated.

I've attached code for my coin tosser program. I had intended to use this as a basis for this new bias coin tossing program.

// CoinTosser_Homework4.cpp : Coin tossing program
// nxt3

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#define HEADS 0
#define TAILS 1

int rand_int(int a, int b) {

return rand() % ((b - a + 1) + a);
}

int main() {

int tosses = 0, min = 0, heads = 0, tails = 0; //init tosses and number of user defined tosses

/*users input for number of tosses*/
printf("Enter number of coin tosses: ");
scanf("%i", &min);

while (tosses < min) {
    tosses++;
    if (rand_int(HEADS, TAILS) == HEADS)
        heads++;
    else
        tails++;
}

//prints results of tosses
printf("Number of heads: %i\n", heads);
printf("Number of tails: %i\n", tails);

return 0;
}

回答1:

Do it the old fashioned way:

rand() % 100 + 1;

gives you a number in the range 1 to 100 (inclusive). It's heads if that number is less than or equal to 55.

But note that this generator is biased unless the periodicity of the generator is a multiple of 100 (which is probably isn't). What you should really do is use something like

(int)(100.0 * rand() / (RAND_MAX + 1.0)) + 1

The 100.0 also circumvents integer division.



回答2:

I forgot the syntax for C, but I can provide you the solution in C++. From here you can see the algorithm.

#include <cstdlib>
#include <iostream>
#include <ctime>
using namespace std;

int main()
{
    int heads=0, tails=0;
    srand(time(NULL));
    number = rand() % 100 + 1;  //Generate random number 1 to 100
          if (number <= 55) //55% chance
                heads++; //This is head
          else
                tails++; //This is tail
}

Explanation: Since using the usual random number will gives you a normal distribution instead of a poisson number distribution, you are safe to use condition if (number <= 55) to generate a probability of 55% chance.



标签: c loops random