Post Reply 
little math/programming problems April 2023
05-02-2023, 08:03 PM
Post: #5
RE: little math/programming problems April 2023
(04-29-2023 06:50 PM)Allen Wrote:  
  • 5.490012 expected rolls on average
I'm surprised that we came up with such different answers. With 10 million trials, I got an average of 5.49603. Here's my C++ code. Does anyone spot a problem? Maybe this is a case of rand() showing it's limitations?
Code:
#include<iostream>                               //Required for cin, cout
#include<cmath>
using namespace std;
int
main()
{
    int sides[6] = {0,0,0,0,2,3};
    int N, D;
    int totalRolls = 0;
    cout << "Enter starting number of dice and number of simulations: ";
    cin >> D >> N;

    for (int i=0; i<N; ++i) {
        int sum = D, count=0;
        int dice;
        for (count=0; (dice = sum); ++count) {  // note that (dice=sum) is assignment, not comparison
            for (int i=sum=0; i<dice; ++i) {
                int side = sides[rand() % 6];
                sum += side;
            }
        }
        totalRolls += count;
    }
    cout << "Average of " << (double)totalRolls/N << " rolls starting with " << D << " dice\n";
}

$ ./foo
Enter starting number of dice and number of simulations: 5 10000000
Average of 5.49603 rolls starting with 5 dice
Find all posts by this user
Quote this message in a reply
Post Reply 


Messages In This Thread
RE: little math/programming problems April 2023 - David Hayden - 05-02-2023 08:03 PM



User(s) browsing this thread: 1 Guest(s)