In: Computer Science
In this lab we will write 3 functions:
GenData: This function will take an integer parameter and return a vector with that many random integers generated in the range of 0 and 100 (rand()%101). Seed the random number generator with 22.
Mean(): This function will take a vector and return the
mean.
Variance(): This function will take a vector and return the
population variance, as: [Sum for values[( x_i - Mean )^2]] /
(number of items)
In Main:
Example Output:
83, 89, 54, 38, 2, 84, 47, 88, 78, 55,
Mean=51.62
Variance=905.08
Given:
#include <iostream>
#include <vector>
#include <cstdlib>
#include <iomanip>
#include <cmath>
using namespace std;
vector<int> GenData(int n){
//should generate n random values and return them.
}
double Mean(vector<int> d){
unsigned int i;
//return mean of all values in vector.
}
/*Variance function
sum +=(your current X value - mean)^2
return variance - > [ sum/total size of vector]
*/
int main(){
int i;
vector<int> d;
d = GenData(100);
for (/*loop for 10 values*/){
cout << d.at(i) << ", " ;
}
return 0;
}
in c++ pls
Code:
#include <iostream>
#include <vector>
#include <cstdlib>
#include <iomanip>
#include <cmath>
using namespace std;
vector<int> GenData(int n) {
//should generate n random values and return them.
srand(22); // set seed to 22
vector <int> v;
// generate n numbers
for(int i=0;i<n;i++){
int x = rand()%101;
v.push_back(x);
}
return v;
}
double Mean(vector<int> d) {
int n = d.size(); // no. of elements in vector
unsigned int i = 0; // use to store sum
for(int j=0;j<n;j++){
i+= d[j]; // add values to sum
}
// mean = sum of all no. / size
double mean = i/(n*1.0);
//return mean of all values in vector.
return mean;
}
/*Variance function
sum +=(your current X value - mean)^2
return variance - > [ sum/total size of vector]
*/
double Variance(vector <int> d){
double mean = Mean(d); // find out mean
double sum = 0;
int n = d.size(); // no. of elements
for(int i=0;i<n;i++){
sum += (d[i]-mean)*(d[i]-mean); // add ( x_i - Mean )^2
}
// divide by no. of items to find variance
double var = sum/n;
return var;
}
int main() {
int i;
vector<int> d;
d = GenData(100);
for (int i=0;i<10;i++) {
cout << d.at(i) << ", " ;
}
cout<<endl;
double mean = Mean(d);
double var = Variance(d);
cout<<"Mean="<<mean<<endl;
cout<<"Variance="<<var<<endl;
return 0;
}
Code Screenshot:
Code output:
==========================
Code along with screenshots and comment has been added.
Please upvote.