Write a program to generate the histogram for the random number generator. Creat
ID: 3807421 • Letter: W
Question
Write a program to generate the histogram for the random number generator. Create 10 counters with the following limits: First initialize each counter to zero. Generate a random number between 0 and 1. Increment the corresponding counter by 1. Repeat this 10, 000 times. Whenever the random number generated falls in a particular range increment the corresponding counter bin by one. Plot the counter frequencies(i.e. the histogram) Modify the program to plot the histogram of the sum of 10 random numbers. create 10 counters with the following limits:Explanation / Answer
Here is the code for your first problem:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand(time(0));
//Create 10 counters.
int counters[10];
//Initialize each counter to zero.
for(int i = 0; i < 10; i++)
counters[i] = 0;
//Generate random numbers between 0 and 1. Increment corresponding counter.
//Repeat this 10,000 times.
for(int i = 0; i < 10000; i++)
{
double x = (double)rand() / RAND_MAX;
if(x < 0.1)
counters[0]++;
else if(x < 0.2)
counters[1]++;
else if(x < 0.3)
counters[2]++;
else if(x < 0.4)
counters[3]++;
else if(x < 0.5)
counters[4]++;
else if(x < 0.6)
counters[5]++;
else if(x < 0.7)
counters[6]++;
else if(x < 0.8)
counters[7]++;
else if(x < 0.9)
counters[8]++;
else
counters[9]++;
}
for(int i = 0; i < 10; i++)
{
cout << i/10.0 << "-" << (i+1)/10.0 << " ";
for(int j = 0; j < counters[i]/100; j++)
cout << "*";
cout << endl;
}
}
Here is the modified version for the second problem:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand(time(0));
//Create 10 counters.
int counters[10];
//Initialize each counter to zero.
for(int i = 0; i < 10; i++)
counters[i] = 0;
//Generate random numbers between 0 and 1. Increment corresponding counter.
//Repeat this 10,000 times.
for(int i = 0; i < 1000; i++)
{
double sum = 0.0, x;
for(int j = 0; j < 10; j++)
{
x = (double)rand() / RAND_MAX;
sum += x;
}
if(sum < 1)
counters[0]++;
else if(sum < 2)
counters[1]++;
else if(sum < 3)
counters[2]++;
else if(sum < 4)
counters[3]++;
else if(sum < 5)
counters[4]++;
else if(sum < 6)
counters[5]++;
else if(sum < 7)
counters[6]++;
else if(sum < 8)
counters[7]++;
else if(sum < 9)
counters[8]++;
else
counters[9]++;
}
for(int i = 0; i < 10; i++)
{
cout << i << "-" << (i+1) << " ";
for(int j = 0; j < counters[i]/10.0; j++)
cout << "*";
cout << endl;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.