Averaging Coin Tosses with Accumulator C++ - c++

This is the problem I am working with
Using a loop and rand(), simulate a coin toss 10000 times
Calculate the difference between heads and tails.
Wrap the above two lines in another loop, which loops 1000 times.
Use an accumulator to sum up the differences
Calculate and display the average difference between the number of heads and tails.
The accumulator is not working the way I want It to? Very much a C++ Noob, for homework lol. Anyone help please?
Why am I using rand()????
second part of the assignment has us using the newer method (mt19937), just trying to tackle this bit first before moving on.
#include <iostream>
using namespace std;
int main() {
int heads = 0, tails = 0, num, total = 0;
srand(time(NULL));
for (int h = 0; h < 1000; h++) // Loop Coin Toss
{
for (int i = 0; i < 10000; i++) // COIN TOSS
{
int random = rand() % 2;
if (random == 0)
{
heads++;
}
else
{
tails++;
}
}
cout << abs((heads++ - tails++));
cin >> num;
total =+ num;
}
cout << "The average distance between is " << total / 1000 << endl;
cin.get();
return 0;
}

With your code, you never actually save the values that you need. And there's some unnecessary arithmetic that would throw off your results. This line:
cout << abs((heads++ - tails++)); increments the heads and tails variables, but they shouldn't be.
The next two lines make no sense. Why do you need to get a number from the user, and why do you add that number to your total?
Finally, this expression: total / 1000 performs integer division, which will throw off your results.
Those are the immediate issues I can spot in your code.
Next, we move on to your problem statement. What is an accumulator? To me, it sounds like you're supposed to have a class? It also reminds me of std::accumulate, but if that's what you intended, it would have said as much. Also, std::accumulate would require storing results, and that's not really necessary for this program. The code below performs the main task, i.e. it runs the necessary simulations and tracks results.
You'll notice I don't bother counting tails. The big average is also calculated as it goes since the total number of simulations is known ahead of time.
#include <cmath>
#include <iostream>
#include <random>
int flip_coin() {
static std::mt19937 prng(std::random_device{}());
static std::uniform_int_distribution<int> flip(0, 1);
return flip(prng);
}
int main() {
constexpr int tosses = 10'000;
constexpr int simulations = 1'000;
double diffAvg = 0.0;
for (int i = 0; i < simulations; ++i) {
int heads = 0;
for (int j = 0; j < tosses; ++j) {
if (flip_coin()) {
++heads;
}
}
diffAvg +=
std::abs(heads - (tosses - heads)) / static_cast<double>(simulations);
}
std::cout << "The average heads/tails diff is: " << diffAvg << '\n';
return 0;
}

What I ended up doing that seems to work for **THIS VERSION WITH RAND() (using the new method later) **
#include <iostream>
using namespace std;
int main()
{
int heads = 0, tails = 0, total = 0;
srand(time(NULL));
for (int h = 0; h < 1000; h++) // Loop Coin Toss
{
{
for (int i = 0; i < 10000; ++i) // COIN TOSS
if (rand() % 2 == 0)
++heads;
else
++tails;
total += abs(heads - tails);
}
}
cout << "The average distance between is " << total / 1000.0 << '\n';
cin.get();
return 0;
}

Related

Arriving at a close approximation of the probability using code

I was given a math question on probability. It goes like this:
There are 1000 lotteries and each has 1000 tickets. You decide to buy 1 ticket per lottery. What is the probability that you win at least one lottery?
I was able to do it mathematically on paper (arrived at 1 - (999/1000)^1000), but an idea of carrying out large iterations of the random experiment on my computer occurred to me. So, I typed some code — two versions of it to be exact, and both malfunction.
Code 1:
#include<iostream>
#include <stdlib.h>
using namespace std;
int main() {
int p2 = 0;
int p1 = 0;
srand(time(NULL));
for (int i = 0; i<100000; i++){
for(int j = 0; j<1000; j++){
int s = 0;
int x = rand()%1000;
int y = rand()%1000;
if(x == y)
s = 1;
p1 += s;
}
if(p1>0)
p2++;
}
cout<<"The final probability is = "<< (p2/100000);
return 0;
}
Code 2:
#include<iostream>
#include <stdlib.h>
using namespace std;
int main() {
int p2 = 0;
int p1 = 0;
for (int i = 0; i<100000; i++){
for(int j = 0; j<1000; j++){
int s = 0;
srand(time(NULL));
int x = rand()%1000;
srand(time(NULL));
int y = rand()%1000;
if(x == y)
s = 1;
p1 += s;
}
if(p1>0)
p2++;
}
cout<<"The final probability is = "<< (p2/100000);
return 0;
}
Code 3 (refered to some advanced text, but I don't understand most of it):
#include<iostream>
#include <random>
using namespace std;
int main() {
int p2 = 0;
int p1 = 0;
random_device rd;
mt19937 gen(rd());
for (int i = 0; i<100000; i++){
for(int j = 0; j<1000; j++){
uniform_int_distribution<> dis(1, 1000);
int s = 0;
int x = dis(gen);
int y = dis(gen);
if(x == y)
s = 1;
p1 += s;
}
if(p1>0)
p2++;
}
cout<<"The final probability is = "<< (p2/100000);
return 0;
}
Now, all of these codes output the same text:
The final probability is = 1
Process finished with exit code 0
It seems that the rand() function has been outputting the same value over all the 100000 iterations of the loop. I haven't been able to fix this.
I also tried using randomize() function instead of the srand() function, but it doesn't seem to work and gives weird errors like:
error: ‘randomize’ was not declared in this scope
randomize();
^
I think that randomize() has been discontinued in the later versions of C++.
I know that I am wrong on many levels. I would really appreciate if you could patiently explain me my mistakes and let me know some possible corrections.
You should reset your count (p1) at the beginning of the outer loop. Also, be aware of the final integer division p2/100000, any value of p2 < 100000 would result in 0.
Look at this modified version of your code:
#include <iostream>
#include <random>
int main()
{
const int number_of_tests = 100000;
const int lotteries = 1000;
const int tickets_per_lottery = 1000;
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> lottery(1, tickets_per_lottery);
int winning_cases = 0;
for (int i = 0; i < number_of_tests; ++i )
{
int wins = 0; // <- reset when each test start
for(int j = 0; j < lotteries; ++j )
{
int my_ticket = lottery(gen);
int winner = lottery(gen);
if( my_ticket == winner )
++wins;
}
if ( wins > 0 )
++winning_cases;
}
// use the correct type to perform these calculations
double expected = 1.0 - std::pow((lotteries - 1.0)/lotteries, lotteries);
double probability = static_cast<double>(winning_cases) / number_of_tests;
std::cout << "Expected: " << expected
<< "\nCalculated: " << probability << '\n';
return 0;
}
A tipical run would output something like:
Expected: 0.632305
Calculated: 0.63125
Only seed the pseudorandom number generator by srand once at the beginning of your program. When you seed it over and over again you reset the pseudorandom number generator to the same initial state. time has a granularity measured in seconds, by default. Odds are you are getting all 1000 iterations - or most of them - within a single second.
See this answer to someone else's question for a general description of how pseudorandom number generators work.
This means that you should be creating one instance of a PRNG in your program and seeding it one time. Don't do either of those tasks inside loops, or inside functions that get called multiple times, unless you really know what you're doing and are trying to do something sophisticated such as using correlation induction strategies such as common random numbers or antithetic variates to achieve "variance reduction".

Using structs / genetic algorithm

As practice for myself I'm trying to create a genetic algorithm that will solve equations. So far my program can generate random "genes", fill up individuals with these "genes", and do some basic calculations with the genes (at the moment, simply summing the "genes").
However, I've realised now that I want to implement my fitness function that I would have been better off creating a struct for individual, since I need to keep the genes and the fitness outcome together to have the fittest genes reproduce again.
Anyway, here's my code:
// GA.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <random>
#include <string>
const int population_size = 10;
const int number_of_variables = 7;
struct one_individual
{
std::vector<std::vector<double>>individual;;
double evaluation = 0;
double fit = 0;
};
int main()
{
// Generate random number
std::random_device rd;
std::mt19937 rng(rd()); // random-number engine (Mersenne-Twister in this case)
std::uniform_real_distribution<double> dist(-10.0, 10.0);
// Create vector that holds vectors called individual and fill size it to the amount of individuals I want to have.
std::vector<std::vector<double>>individual;
for (int i = 0; i < population_size; i++)
{
std::vector<double>variables;
for (int j = 0; j < number_of_variables; j++)
{
variables.push_back(dist(rng));
}
individual.push_back(variables);
}
// Display entire population
for (auto &count : individual)
{
for (auto &count2 : count)
{
std::cout << count2 << " ";
}
std::cout << "\n";
}
// Do calculation with population. At the moment I just add up all the genes (sum) and display the sum for each individual.
for (int i = 0; i < population_size; i++)
{
int j = 0;
std::cout << "Organism "<< i;
double sum = individual[i].at(j) + individual[i].at(j + 1) + individual[i].at(j + 2) + individual[i].at(j + 3) + individual[i].at(j + 4) + individual[i].at(j + 5) + individual[i].at(j + 6);
std::cout << " is " << sum << "\n";
}
std::cout << "\n";
return 0;
}
What I think I should be doing is something like this:
for (int i = 0; i < population_size; i++)
{
one_individual individual;
std::vector<double>variables;
for (int j = 0; j < number_of_variables; j++)
{
variables.push_back(dist(rng));
}
one_individual.individual.push_back(variables);
}
The above code is not working. What happens when I try to compile is I get a list of errors, I just pasted it into pastebin since it's a pretty big list: www.pastebin.com/EVJaV0Ex. If I remove everything except the parts needed for the "creating individuals part" the errors that remain are: www.pastebin.com/djw6JmXZ. All errors are on line 41 which is the final line one_individual.individual.push_back(variables);
Edited for clarity, apologies that it was unclear.
Consider the instruction
one_individual.individual.push_back(variables);
where one_individual is a type (struct one_individual).
I suppose you should use the defined variable of type one_individual, so
individual.individual.push_back(variables);

Passing 2D array Random Number Generator into main with C++

Hi guys I'm very new to C++ and was wondering if you guys could help me. Right now I'm just going by the book and what the teacher told me to do so some of the stuff might look different.
What I want to do is have my void random generator put numbers into my 2D array and then it goes into main. Then I have it pass through into my display function but for some reason I can't get it work right. Can you guys help me out?
edit: Ok I figured that it has something to do with my random number generator not putting the numbers into the array but not sure why. Since my number generator works find with 1D Array.
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <iomanip>
using namespace std;
//Globral Varaibles Must be on top
const int max = 100;
const int min = 1;
const int COL = 4;
const int Rows = 3;
//Functions
void Population(int Array[][COL], int size);
void Show(const int Array[][COL], int max);
int main()
{
int a[3][4];
Population(a, Rows);
Show(a, Rows);
}
void Population( int Array[][COL], int size)
{
for (int index = 0; index < Rows; index++)
{
for (int Count = 0; Count < COL; Count++)
{
unsigned seed = time(0);
Array[index][Count] = (rand() % (max - min + 1)) + min;
}
}
}
void Show(const int a[][COL], int Rows)
{
for (int i = 0; i < Rows; i++)
{
for (int J = 0; J < COL; J++)
{
cout << setw(4) << a[i][J] << endl;
}
}
cout << endl;
cout << endl;
}
You seem to be seeding your random number generator every time you enter your second for loop in population(). You should only seed a random number generator once in a program, near the beginning.
Try removing your seed line from population() and instead using
srand(time(NULL));
at the beginning of your main()
AH, I figured out the problem. I had been mistaking what was being showing as one giant column instead of it being divided into rows and columns.
I had to have a small space after the a[i][J] part so that it could be divided into rows and columns.
cout << setw(4) << a[a][J] << " ";
That_Knight_Guy thanks for the suggestion. Now my generator finally puts out random numbers.

Calculating a conditional probability that is similar to a binomial sum

I am considering a society where there are an arbitrary number of people. Each person has just two choices. Either he or she stays with her current choice or she switches. In the code that I want to write, the probability that the person switches is inputted by the user.
To make clear what I am trying to do, suppose that the user tells the computer that there are 3 people in the society where the probabilities that each person chooses to switch is given by (p1,p2,p3). Consider person 1. He has probability of p1 of switching. Using him as a base for our calculation, the probability given person 1 as a base, that exactly no one in the society chooses to switch is given by
P_{1}(0)=(1-p2)*(1-p3)
and the probability using person 1 as a base, that exactly one person in the society chooses to switch is given by
P_{1}(1)=p2*(1-p3)+(1-p2)*p3.
I can't figure out how to write this probability function in C++ without writing out every term in the sum. I considered using the binomial coefficient but I can't figure out a closed form expression for the sum since depending on user input, there are arbitrarily many probabilities that need to be considered.
I have attached what I have. The probability function is only a part of what I am trying to do but it is also the hardest part. I named the probability function probab and what I have in the for loop within the function is obviously wrong.
EDIT: Basically I want to calculate the probability of choosing a subset where each element in that subset has a different probability of being chosen.
I would appreciate any tips on how to go about this. Note that I am a beginner at C++ so any tips on improving my programming skills is also appreciated.
#include <iostream>
#include <vector>
using namespace std;
unsigned int factorial(unsigned int n);
unsigned int binomial(unsigned int bin, unsigned int cho);
double probab(int numOfPeople, vector<double> probs, int p, int num);
int main() {
char correctness;
int numOfPeople = 0;
cout << "Enter the # of people: ";
cin >> numOfPeople;
vector<double> probs(numOfPeople); // Create a vector of size numOfPeople;
for (int i = 1; i < numOfPeople+1; i++) {
cout << "Enter the probability of person "<< i << " will accept change: ";
cin >> probs[i-1];
}
cout << "You have entered the following probabilities of accepting change: (";
for (int i = 1; i < numOfPeople+1; i++) {
cout << probs[i-1];
if (i == numOfPeople) {
cout << ")";
}
else {
cout << ",";
}
}
cout << endl;
cout << "Is this correct? (Enter y for yes, n for no): ";
cin >> correctness;
if (correctness == 'n') {
return 0;
}
return 0;
}
unsigned int factorial(unsigned int n){ // Factorial function
unsigned int ret = 1;
for(unsigned int i = 1; i <= n; ++i) {
ret *= i;
}
return ret;
}
unsigned int binomial(unsigned int totl, unsigned int choose) { // Binomial function
unsigned int bin = 0;
bin = factorial(totl)/(factorial(choose)*factorial(totl-choose));
return bin;
}
double probab(int numOfPeople, vector<double> probs, int p, int num) { // Probability function
double prob = 0;
for (int i = 1; i < numOfPeople; i++) {
prob += binomial(numOfPeople, i-1)/probs[p]*probs[i-1];
}
return prob;
}
For future reference, for anybody attempting to do this, the probability function will look something like:
double probability (vector<double> &yesprobabilities, unsigned int numOfPeople, unsigned int yesNumber, unsigned int startIndex) {
double kprobability = 0;
// Not enough people!
if (numOfPeople-1 < yesNumber) {
kprobability = 0;
}
// n == k, the only way k people will say yes is if all the remaining people say yes.
else if (numOfPeople-1 == yesNumber) {
kprobability = 1;
for (int i = startIndex; i < numOfPeople-1; ++i) {
kprobability = kprobability * yesprobabilities[i];
}
}
else if (yesprobabilities[startIndex] == 1) {
kprobability += probability(yesprobabilities,numOfPeople-1,yesNumber-1,startIndex+1);
}
else {
// The first person says yes, k - 1 of the other persons have to say yes.
kprobability += yesprobabilities[startIndex] * probability(yesprobabilities,numOfPeople-1,yesNumber-1,startIndex+1);
// The first person says no, k of the other persons have to say yes.
kprobability += (1 - yesprobabilities[startIndex]) * probability(yesprobabilities,numOfPeople-1,yesNumber,startIndex+1);
}
return probability;
}
Something called a recursive function is used here. This is completely new to me and very illuminating. I credit this to Calle from Math stack exchange. I modified his version slightly to take vectors instead of arrays with some help.

C++ - Calculate execution time of a function always = 0?

I use clock() in library to calculate excution time of a function, which is BubbleSort(..) function in my code below. But probleam is that the return execution time always = 0 (and it shows no unit, too).
This is my code:
#include <iostream>
#include <ctime>
using namespace std;
void BubbleSort(int arr[], int n)
{
for (int i = 1; i<n; i++)
for (int j = n-1; j >=i; j-- )
if (arr[j] < arr[j-1])
{
int temp = arr[j];
arr[j] = arr[j-1];
arr[j-1] = temp;
}
return;
}
int main()
{
int arr[] = {4,1,7,2,6, 17, 3, 2, 8,1};
int len = sizeof(arr)/sizeof(int);
cout << "Before Bubble Sort: \n";
for (int i=0;i<len;i++)
{
cout << arr[i] << " ";
}
clock_t start_s=clock(); // begin
BubbleSort(arr,len);
clock_t stop_s=clock(); // end
cout << "\nAfter Bubble Sort: \n";
for (int i=0;i<len;i++)
{
cout << arr[i] << " ";
}
// calculate then print out execution time - currently always returns 0 and I don't know why
cout << "\nExecution time: "<< (double)(stop_s - start_s)/CLOCKS_PER_SEC << endl;
//system("pause");
return 0;
}
I haven't known how to fix this problem yet .. So hope you guys can help me with this. Any comments would be very appreciated. Thanks so much in advanced !
As you have only a very small array, the execution time is probably much shorter than the resolution of clock(), so you either have to call the sort algorithm repeatedly or use another time source.
I modified your code as such and both start end stop have the value of 0. (ubuntu 13.10)
std::cout<<"start: "<<start_s<<std::endl;
BubbleSort(arr,len);
clock_t stop_s=clock(); // end
std::cout<<"stop: "<<stop_s<<std::endl;
you probably want something more like gettimeofday()
this http://www.daniweb.com/software-development/cpp/threads/120862/clock-always-returns-0 is an interesting discussion of the same thing. the poster concluded that clock()(on his machine) had a resolution of about 1/100 of a sec. and your code is probably ( almost certainly) running faster than that