0
Write a program to calculate variance and standard deviation of n number
5 Antworten
+ 17
//======================================
// CodeName : SD and variance calculator
// Done for : shuvalaxmi mishra
// By : Babak Sheykhan
// Date : Nov 25, 2017
//
// Input Example:
// 5 <- number of samples
// 20
// 31
// 50
// 69
// 80
//=======================================
#include <iostream>
#include <iomanip>
#include <vector>
#include <numeric>
#include <cmath>
class SD_var {
public:
SD_var(double mean = 0.0, double sDiv = 0.0, double var = 0.0)
: mean(mean), sd(sDiv), variance(var) { }
void get_samples();
void calculate();
void printing() const;
private:
std::vector<int> _data;
double mean;
double sd;
double variance;
};
void SD_var::get_samples() {
int samples = 0, input = 0;
std::cout << "How many sample do we have? ";
std::cin >> samples;
for (auto i = 0; i < samples; ++i) {
std::cout << "Sample # " << i + 1 << ": ";
std::cin >> input;
_data.push_back(input);
}
}
void SD_var::calculate() {
int sum = std::accumulate(_data.begin(), _data.end(), 0);
mean = sum / _data.size();
double sq_sum = 0.0;
for (const auto &i : _data)
sq_sum += pow(i - mean, 2);
sd = sqrt(sq_sum / (_data.size() - 1));
variance = sd * sd;
}
void SD_var::printing() const {
std::cout << "\nSamples are :\n";
for (const auto &i : _data)
std::cout << std::setw(5) << i;
std::cout << "\n------------------------\n";
std::cout << "Mean : " << mean << std::endl;
std::cout << "SD : " << sd << std::endl;
std::cout << "Variance : " << variance << std::endl;
std::cout << "------------------------\n";
}
int main() {
SD_var test;
test.get_samples();
test.calculate();
test.printing();
}
Possible output:
Samples are :
20 31 50 69 80
------------------------
Mean : 50
SD : 25.1098
Variance : 630.5
------------------------
[https://code.sololearn.com/ctJ7B3buZDty]
+ 13
Homework?
+ 4
@Shuvalaxmi Try to create your own code and ask us to review it
+ 2
@Shuvalaxmi, here it is:
https://code.sololearn.com/cviiA0jiY4ku/?ref=app
0
Find the variance and standard deviation of probability distribution of the random variable x if P (×)=×+1/20 for x =1,2,3,4,5,