Thread: Calculating standard deviation(file I/O)

  1. #1
    new to c++
    Join Date
    Feb 2009
    Posts
    53

    Calculating standard deviation(file I/O)

    hello

    I am writing a program that needs to calculate the average of numbers and the standard deviation of numbers, the numbers are input by the user.The program takes the numbers that the user enters and outputs them to a text file, then the program reads in the numbers and calculates the average of them. then the program closes the file. It then reopens and calculates the standard deviation outputs the number and then closes.
    the standard deviation is calculated as:
    sqrt((n1-avg.)^2+(n2-avg)^2+(n3-avg)^2+.../howmanynumbers)

    My question is how would i get the values n1,n2,n3 and so forth if I entered the numbers as the variable 'numbers'. is there a way to just read one number at a time? This is what I got so far
    Code:
    #include<iostream>
    #include<fstream>
    #include<cstdlib>
    #include<cmath>
    using namespace std;
    
    void asknumbers(ofstream& myfile,int& howmanynumbers,double& numbers);
    void readnumbers(ifstream& outfile, double numbers, double& total,int howmanynumbers,double& average);
    void standarddev(ifstream& outfile, double numbers,double average,double& standardd, int howmanynumbers);
    
    
    int main()
    {
    	ofstream myfile;
    	ifstream outfile;
    	int howmanynumbers;
    	double numbers,total,average,standardd;
    	char repeat;
    
    	do
    	{
    		
    
    		myfile.open("numbers_file.txt",ios::trunc);					//opens and deletes everything from before
    		myfile.close();												//closes file
    
    		asknumbers(myfile,howmanynumbers,numbers);					//function for asking numbers
    		readnumbers(outfile,numbers,total,howmanynumbers,average);	//function for total and average
    		standarddev(outfile,numbers,average,standardd,howmanynumbers);//function for standard deviation
    		
    	
    
    		cout<<"Do you want to repeat: ";
    		cin>>repeat;
    		
    
    		system("cls");
    	}while(repeat=='y'||repeat=='Y');								//end first do loop
    
    	system("pause");
    	return 0;
    }
    
    
    
    void asknumbers(ofstream& myfile,int& howmanynumbers,double& numbers)
    {
    
    	cout<<"how many numbers do you want to input:";					//asks how many number i want to put in
    	cin>>howmanynumbers;
    
    	int numbercounter;
    	numbercounter=howmanynumbers;
    
    		do															//asks for the numbers
    		{
    
    			cout<<"enter the numbers:";
    			cin>>numbers;
    
    			myfile.open ("numbers_file.txt",ios::app);				//writes to file called numbers_file.txt
    			myfile<<numbers<<endl;									//writes numbers to the file
    			myfile.close();											//closes file
    
    			numbercounter--;										//counts down how many numbers put in
    
    		}while(numbercounter>=1);									//ends asking for numbers
    }
    
    
    void readnumbers(ifstream& outfile,double numbers, double& total,int howmanynumbers,double& average)
    {
    	total=0;
    	outfile.open("numbers_file.txt");								//opens file
    	for(int x=howmanynumbers;x>0;x--)
    	{
    		outfile>>numbers;											//reads numbers
    		total+=numbers;												//calculates total from numbers input
    		average=total/howmanynumbers;
    
    	}
    												
    	cout<<"The total of the numbers is: "<<total<<endl;
    	cout<<"The average of the "<<howmanynumbers<<" numbers is: "<<average<<endl;
    
    }
    void standarddev(ifstream& outfile, double numbers,double average,double& standardd,int howmanynumbers)
    {
    	outfile.open("numbers_file.txt");								//opens file
    	for(int x=howmanynumbers;x>0;x--)
    	{
    		standardd=sqrt(pow((numbers-average),2)/average);
    	}
    	cout<<"The standard deviation of those numbers is: "<<standardd<<endl;
    }

  2. #2
    Registered User
    Join Date
    Oct 2010
    Posts
    18
    Lucky for you I just worked out a thing like this for an application I'm writing to study financial data (statistical-like things, har har).

    Say you got a CSV file with a set of elements, "1,2,3,4", and the data grouped on separate lines.... and you want to import this in to an array of floats. Here's what you can do:

    (Modify this code as required by your data format, that part should be trivial so good luck!)

    Code:
    // You'll need this mess here
    #include <vector>
    #include <fstream>
    #include <sstream>
    #include <string>
    
    // int Main() or some other void Stuff() {
    
    // Data
    ifstream ifile ("data.csv");
    
    // Some storage and crap
    string line;
    vector<string> spltstr;
    vector<float> fdata;
    vector< vector<float> > data;
    
    // We'll be using this to convert strings to float
    stringstream ss;
    float fval;
    
    // Open the data file
    if (ifile.is_open())
    {
    	// Process until we hit the end of the file
    	while (!ifile.eof())
    	{
    		// Grab the next line
    		getline(ifile, line);
    
    		// a function to split the line and return an vector<string>
    		spltstr = splitString(&line, ',');
    
    		// Go through each element of the split string, converting it to a float
    		// Then adding that float to a new vector
    		fdata.clear();
    		for (int j = 0; j < splitstr.size(); ++j)
    		{
    			ss.str(""); ss.clear();
    			ss << spltstr[j];
    			ss >> fval;
    			fdata.push_back(fval);
    		}
    
    		// Save our converted floats to this 2d vector
    		data.push_back(fdata);
    	}
    }
    
    // Now you have a 2d vector of floats from the CSV
    // data[0] = {1.0, 2.0, 3.0, 4.0};
    // data[0][0] = 1.0;
    // etc...
    
    // So loop through those values in the array and average it up or something, what ever.

    Here's a crude string split function, it's not pretty but it does the job;

    Code:
    vector<string> splitString(string* s, char del)
    {
    	vector<string> res;
    	string st;
    	for (int j = 0; j < s->size(); ++j)
    	{
    		if ((*s)[j] == del)
    		{
    			res.push_back(st);
    			st = "";
    		}
    		else
    		{
    			st += (*s)[j];
    		}
    
    		if (j == (s->size() - 1))
    		{
    			if (st != "")
    			{
    				res.push_back(st);
    			}
    		}
    	}
    	return res;
    }
    Last edited by syneii; 11-09-2010 at 05:11 PM.

  3. #3
    new to c++
    Join Date
    Feb 2009
    Posts
    53

    file i/o help with standard deviation calculation

    hello

    I am writing a program that will take numbers entered by the user and calculate the average and standard deviation of those numbers. the program takes the numbers entered and outputs them to a text file then reads them and calculates them.
    I am stumped on how to calculate the standard deviation with the way I enter the numbers. could I please get some hints or something about it.
    basically I dont know how to get the 'numbers' variable for the standarddev function. the program returns '-1.#ind' for the standard deviation, which i know is wrong.
    the standard deviation formula is the square root of the average of
    (n1-avg)^2+(n2-avg)^2+(n3-avg)^2+...
    where n1=the first number i entered,n2=the second number,n3=the third number,and so on.

    Code:
    #include<iostream>
    #include<fstream>
    #include<cstdlib>
    #include<cmath>
    using namespace std;
    
    void asknumbers(ofstream& myfile,int& howmanynumbers,double& numbers);
    void readnumbers(ifstream& outfile, double numbers, double& total,int howmanynumbers,double& average);
    void standarddev(ifstream& outfile,double numbers,double average,double& standardd, int howmanynumbers,double& numbers1);
    
    
    int main()
    {
    	ofstream myfile;
    	ifstream outfile;
    	int howmanynumbers;
    	double numbers,total,average,standardd,numbers1;
    	char repeat;
    
    	do
    	{
    		
    
    		myfile.open("numbers_file.txt",ios::trunc);					//opens and deletes everything from before
    		myfile.close();												//closes file
    
    		asknumbers(myfile,howmanynumbers,numbers);					//function for asking numbers
    		readnumbers(outfile,numbers,total,howmanynumbers,average);	//function for total and average
    		standarddev(outfile,numbers,average,standardd,howmanynumbers,numbers1);//function for standard deviation
    		
    	
    
    		cout<<"Do you want to repeat: ";
    		cin>>repeat;
    		
    
    		system("cls");
    	}while(repeat=='y'||repeat=='Y');								//end first do loop
    
    	system("pause");
    	return 0;
    }
    
    
    
    void asknumbers(ofstream& myfile,int& howmanynumbers,double& numbers)
    {
    
    	cout<<"how many numbers do you want to input:";					//asks how many number i want to put in
    	cin>>howmanynumbers;
    
    	int numbercounter;
    	numbercounter=howmanynumbers;
    
    		do															//asks for the numbers
    		{
    
    			cout<<"enter the numbers:"<<endl;
    			cin>>numbers;
    
    			myfile.open ("numbers_file.txt",ios::app);				//writes to file called numbers_file.txt
    			myfile<<numbers<<endl;									//writes numbers to the file
    			myfile.close();											//closes file
    
    			numbercounter--;										//counts down how many numbers put in
    
    		}while(numbercounter>=1);									//ends asking for numbers
    }
    
    
    void readnumbers(ifstream& outfile,double numbers, double& total,int howmanynumbers,double& average)
    {
    	total=0;
    	outfile.open("numbers_file.txt");								//opens file
    	for(int x=howmanynumbers;x>0;x--)
    	{
    		outfile>>numbers;											
    		total+=numbers;												//calculates total from numbers input
    		average=total/howmanynumbers;
    
    	}
    												
    	cout<<"The total of the numbers is: "<<total<<endl;
    	cout<<"The average of the "<<howmanynumbers<<" numbers is: "<<average<<endl;
    
    }
    void standarddev(ifstream& outfile,double numbers,double average,double& standardd,int howmanynumbers,double& numbers1)
    {
    	outfile.open("numbers_file.txt");	//opens file
    
    	for(int x=howmanynumbers;x>0;x--)
    	{
    		numbers1+= pow((numbers-average),2);
    	}
    	standardd=sqrt(numbers1/howmanynumbers);		//sqrt of average of all things
    
    	cout<<"The standard deviation of those numbers is: "<<standardd<<endl;	
    }

  4. #4
    Registered User
    Join Date
    Oct 2010
    Posts
    18
    Why was my response removed?

    rfoor, did you get my code before they deleted my post?

    Apparently they got really angry at me for giving you code in my reply.
    Last edited by syneii; 11-10-2010 at 09:00 AM.

  5. #5
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by syneii
    Why was my response removed?
    Your response was not removed; rfoor started a second thread on the same topic, but with slightly different wording and code snippets. I have merged the threads, but due to these differences I chose to keep both the original posts.

    rfoor, please do not double post in the future.

    Quote Originally Posted by syneii
    Apparently they got really angry at me for giving you code in my reply.
    If you can deduce this, then you probably feel guilty about spoonfeeding. In this case, I think that the example you provided is fine, especially since rfoor did make some effort to post code, but if you do feel such guilt, then you should not have posted code in the first place.

    Incidentally, this part of your code is wrong:
    Code:
    	// Process until we hit the end of the file
    	while (!ifile.eof())
    	{
    		// Grab the next line
    		getline(ifile, line);
    It should be:
    Code:
    	// Process until we hit the end of the file
    	while (getline(ifile, line))
    	{
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. array initialization & C standard
    By jim mcnamara in forum C Programming
    Replies: 2
    Last Post: 09-12-2008, 03:25 PM
  2. Bug in iterator comparison in C++ standard?
    By steev in forum C++ Programming
    Replies: 14
    Last Post: 07-12-2008, 12:02 AM
  3. Replies: 8
    Last Post: 03-08-2008, 08:50 PM
  4. Looping and I/O Stream
    By Unregistered in forum C++ Programming
    Replies: 3
    Last Post: 09-07-2001, 10:20 AM
  5. standard language, standard compiler?
    By doubleanti in forum A Brief History of Cprogramming.com
    Replies: 8
    Last Post: 09-03-2001, 04:21 AM