Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Program to compute mean, standard deviation and standard
- // error of the mean electronic charge. Data is read from file.
- #include<iostream>
- #include<iomanip>
- #include<fstream>
- #include<cmath>
- #include<string>
- #include<sstream>
- using namespace std;
- // Functions to compute mean and standard deviation
- double calcmean(double *data){
- double sum{0};
- int length = sizeof(data);
- for (int i = 0; i < length; i++){
- sum += data[i];
- }
- double mean = sum / (length);
- return mean;
- }
- double calcstddev(double *data){
- double sum{ 0 };
- int length = sizeof(data);
- double sumdev2{ 0 };
- for (int i = 0; i < length; i++){
- sum += data[i];
- }
- double mean = sum / length;
- for (int i = 0;i < length; i++){
- sumdev2 += pow(data[i] - mean, 2);
- }
- double stddev = pow(sumdev2 / (length - 1), 0.5);
- return stddev;
- }
- double strtodbl(string s) {
- double d;
- stringstream ss(s);
- ss >> d;
- return d;
- }
- bool linetest(string input){
- stringstream ss(input);
- double d;
- if (!(ss >> d)){
- return 0;
- }
- return 1;
- }
- // Main function
- int main()
- {
- int datapoints{0};
- string filename;
- /* Ask user to enter number of data points
- cout << "How many data points does your file contain? "; cin >> datapoints;
- while (cin.fail() || datapoints != floor(datapoints) || datapoints < 0){
- cout << "How many data points does your file contain? "; cin.clear(); cin.ignore() >> datapoints;
- }*/
- // Ask user to enter filename
- cout << "What is the name of your file? "; cin >> filename;
- // Open file and check if successful
- fstream myfile(filename);
- if (!myfile.good()) {
- cout << "Error: File could not be opened." << endl;
- }
- // Allocate memory for data
- double *data;
- data = new double[datapoints];
- // Read data from file, ignoring any additional bad data
- string line;
- while (getline(myfile, line)){
- cout << line << endl;
- if (linetest(line)){
- datapoints++;
- }
- }
- cout << "The file contains " << datapoints << " measurements." << endl;
- /*myfile.clear();
- myfile.seekg((0, ios::beg));
- int i{0};
- while (getline(myfile, line)){
- if (linetest(line)){
- data[i] = strtodbl(line);
- i++;
- }
- else{
- cout << "Error encountered: " << line << " is not a valid input" << endl;
- }
- }
- // Close file
- myfile.close();
- //Compute mean
- double mean = calcmean(data);
- // Compute standard deviation
- double stddev = calcstddev(data);
- // Compute standard error of mean
- double stderrmean = calcstddev(data) / pow(datapoints, 0.5);
- cout << "The mean value is: " << mean << endl;
- cout << "standard error on the mean is: " << stddev << endl;
- cout << "The standard deviation is: " << stderrmean << endl;
- // Free memory*/
- delete[] data;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement