Standard deviation calculation outputing incorrectly - c++

I am trying to calculate the standard deviation of an array but my answer is returning as 0. I think the problem is stemming from the "count" getting messed up. The array I am receiving the data from is simply four numbers of 1,4,6,7. The code is outputting the answer as 0 but that is incorrect. Any help would be much appreciated.
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cmath>
#include <string>
using namespace std;
double mean(double *mydata, double N);
double standard_dev(double *mydata, double m, int N);
int main()
{
int N(0);
char filename [100];
double m, stdev;
double next;
int count=0;
cout<<"Enter name of file: ";
cin>>filename;
ifstream myfile;
myfile.open(filename);
while(myfile>>next)
{
count++;
}
N=count;
double *mydata;
mydata=new double[N];
for(int i=0; i<N; i++)
{
myfile>>mydata[i];
}
m = mean(mydata, N);
stdev = standard_dev(mydata, m, N);
cout<<"The standard deviation is:" <<stdev<<endl;
myfile.close();
delete[] mydata;
return 0;
}
double mean(double *mydata, double N)
{
double sum(0), m;
for(int i=0; i<N; i++)
{
sum +=mydata[i];
}
m=(sum/(double)N);
return (m);
}
double standard_dev(double *mydata, double m, int N)
{
double *mydata2= new double [N];
for(int i=0; i<N; i++)
{
mydata2[i]= pow((mydata[i]-m),2);
}
double sum(0), S, X;
for(int i=0; i<N; i++)
{
sum+=mydata2[i];
}
X=sum/N;
S=sqrt(X);
return (S);
}
The code for the array containing the 4 numbers is just:
1
4
6
7
They are vertical in coding.

You are reading in the data wrong. First, you read in all the data to next to increment count. Then you try to read in the nonexistent data with you for loop. I recommend that you use std::vector to avoid the problem of dynamic memory allocation;
vector<double> mydata;
while(myfile>>next)
{
mydata.push_back(next);
}
The other easiest solution is just to put the number of elements in the file. Ex:
File:
4 1 4 6 7
And read N from the file and use your for loop

Related

Reading 2D array from a file and passing it to another function

I wrote down this code in C++ to read a 2D array from a file. Now I'd like to organize better my code with functions. The issue I'm having is that I can't figure out how to pass the 2D array I loaded to memory to another function in the same program.
This is the code I need to organize into functions:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
#define M 4
#define N 4
int main(){
int i, j;
float A[M][N];
string line;
ifstream matrix("matrix.txt");
if (matrix.is_open())
{
do
{
for(i=0; i<M; i++)
{
for(j=0; j<N; j++)
matrix >> A[i][j];
}
}
while (getline(matrix,line));
matrix.close();
}
else cout << "Unable to open file";
float sumline[M]={0};
for(i=0;i<M;i++)
{
for(j=0;j<N;j++)
sumline[i]+=A[i][j];
}
float sumcolumn[N]={0};
for(j=0;j<N;j++)
{
for(i=0;i<M;i++)
sumcolumn[j]+=A[i][j];
}
for (i=0; i<M; i++){
for (j=0; j<N; j++){
if(sumline[i]<sumcolumn[j]){
cout << "Error, total sum of column "<<j<<" is greater than the sum of the line"<<i<<endl;
return 0;
}
}
}
int mincol=sumcolumn[0];
for (i=0; i<N; i++){
if(mincol>sumcolumn[i])
mincol==sumcolumn[i];
}
float avgline = 0.0;
for (i=0; i<M; i++){
avgline=avgline+sumline[i];
}
avgline = avgline/M;
if (avgline * 3 > mincol) {
cout << "Conditions verified"<<endl;
}
else{
cout << "Error, triple of the avg of line is less than the lowest sum of column"<<endl;
return 0;
}
return 0;
}
The code basically does some math on the 2D array. I'd also like to keep as simple as possible so even if using namespace std; it's not really good practice or the way I'm reading the array from the file is really basic I need it to be like that. Thanks a lot.
Instead of using c-array
float A[M][N];
You may instead use
using MyArrayType = std::array<std::array<float>, M>, N>;
MyArrayType A;
Now you can pass by reference (MyArrayType& or const MyArrayType& )
That being said: a c array can be passed as with the more difficult syntax: (float (&a)[M][N]); - it is strongly recommended to use std::array instead where possible.

Greedy Algorithm implemented in fractional knapsack

#include <iostream>
#include<vector>
#include<algorithm>
using namespace std;
double fractional_knapsack(vector<int>& val,vector<int>& wt,int weight)//vectors of values and their respective weights and max weight are passed as parameter
{
int sz=val.size();
vector<double> ratio(sz); //vector to store ratio of values and weights
for(int i=0;i<sz;i++){
ratio[i]=double(val[i]/wt[i]);
}
sort(ratio.begin(),ratio.end(),greater());
//reverse(ratio.begin(),ratio.end());
double max=0.0;
int j=0;
while(max<=weight&&j<sz){
double(weight[j]);
max=max+(ratio[j]*weight[j]);
}
return max;
}
int main()
{ int max_weight,n;
cin>>n>>max_weight;
vector<int>values;
vector<int>weights;
for(int i=0;i<n;i++){
cin>>values[i];
}
for(int i=0;i<n;i++){
cin>>weights[i];
}
double result=fractional_knapsack(values,weights,max_weight);
cout<<"done/n";
cout<<result;
return 0;
}
D:\COdeBlock Projects\Fractional Knapsack\main.cpp|12|error: missing template arguments before '(' token|
it is compiling in devcpp but program_name.exe is crashing
in the method fractional_knapsack(vector<int>& val,vector<int>& wt,int weight) why we pass vector as refrence.
A quick look at the error message reveal the problem lies with the line
sort(ratio.begin(),ratio.end(),greater());
My guess is that you want
sort(ratio.begin(),ratio.end(),greater<double>());
The sort method expects a comparator. If you look at the doc for greater, there's an example on how to use it.
I got the right code.
#include <iostream>
#include<vector>
#include<algorithm>
using namespace std;
double fractional_knapsack(vector<int>& val,vector<int>& wt,int weight)//vectors of values and their respective weights and max weight are passed as parameter
{
int sz=val.size();
vector<double> ratio(sz); //vector to store ratio of values and weights
for(int i=0;i<sz;i++){
ratio[i]=(val[i]/wt[i]);
}
for(int i=0;i<sz;i++){
for(int j=i+1;j<sz;j++){
if(ratio[i]<ratio[j]){
int temp;
temp=ratio[i];
ratio[i]=ratio[j];
ratio[j]=temp;
temp=val[i];
val[i]=val[j];
val[j]=temp;
temp=wt[i];
wt[i]=wt[j];
wt[j]=temp;
}
}
}
//sort(ratio.begin(),ratio.end(),greater<double>());
// sort(val.begin(),val.end(),greater<int>());
//sort(wt.begin(),wt.end(),greater<int>());
//reverse(ratio.begin(),ratio.end());
double max=0.0;
int j=0;
int quantity_left =weight;
while(wt[j]<=quantity_left&&j<sz){
//double(wt[j]);
max=max+(ratio[j]*wt[j]);
cout<<max<<" ";
quantity_left=quantity_left-wt[j];
j++;
}
if(wt[j]>quantity_left&&j<sz){
max=max+(ratio[j]*quantity_left);
// cout<<max<<" ";
}
return max;
}
int main()
{ int max_weight,n;
cin>>n>>max_weight;
vector<int>values(n);
vector<int>weights(n);
for(int i=0;i<n;i++){
cin>>values[i];
}
for(int i=0;i<n;i++){
cin>>weights[i];
}
double result=fractional_knapsack(values,weights,max_weight);
cout<<result;
return 0;
}

Lost data from double and Error: Windows has triggered a breakpoint in exe. This may be due to a corruption of the heap,

I've been working on this code for a while and I almost got it to work but I'm running into a problem. I'm loosing data when it is sorting it. The more number I input the more numbers display a just integers. link to the image of my output
Also once the code runs I'm getting a pop up window with this message (I noticed I get this error after I added the sum function and every function after that and I did not press F12):
"Windows has triggered a breakpoint in project3.exe.
This may be due to a corruption of the heap, which indicates a bug in project3.exe or any of the DLLs it has loaded.
This may also be due to the user pressing F12 while
project3.exe has focus.
The output window may have more diagnostic information.
"
This is my code:
Ask the user for number after the last numbered enter they have to press zero, it display back the data, displays some statistics and sorts the data.
I'm not checking for user error
(*The terminal window closes if I don't use system("pause") so that is why it's there and I know I'm supposed to 'delete []arr but it will give me breakpoint message after I put zero that is why it is comment out)
#include <iostream>
#include <iomanip>
using namespace std;
void getdata(double *arr, double &data, int &floatpt);
void display (double *arr, int floatpt);
void computesum (double *arr, int floatpt, double sum);
void computearthmeticmean (double *arr, int floatpt, double aMean);
void computeharmonicmean (double *arr, int floatpt, double hMean);
void median(double *arr, int floatpt);
void sort (double *arr, int floatpt);
int main ()
{
double data, sum=0, aMean=0, hMean=0;
int count=0, floatpt;
double *arr =new double[count];
getdata (arr, data, floatpt);
cout<<"Thank you. The data you entered are "<<endl;
display(arr, floatpt);
cout<<"The following statistics were computed "<<endl;
computesum(arr,floatpt, sum);
computearthmeticmean(arr, floatpt, aMean);
median(arr, floatpt);
computeharmonicmean (arr, floatpt, hMean);
sort(arr, floatpt);
cout<<"The original data set is "<<endl;
display(arr, floatpt);
cout<<"Thank you for using this program. Enjoy your statistics "<<endl;
//delete []arr;
system ("pause");
return 0;
}
void getdata(double *arr, double &data, int &floatpt)
{
int count=0;
cout<<"Please enter floating point data.\n";
cout<<"After the last number has been entered press 0 (zero) \n";
do
{
cin>>arr[count];
data = arr[count];
count++;
}while(data != 0);
floatpt=(count-1);
}
void display (double *arr, int floatpt)
{
for(int i=0; i<floatpt; i++)
{
cout<<arr[i]<<endl;
}
}
void computesum (double *arr, int floatpt, double sum)
{
for (int j=0; j<floatpt; j++)
{
sum+=arr[j];
}
cout<<"Sum: "<<sum<<endl;
}
void computearthmeticmean (double *arr, int floatpt, double aMean)
{
for (int a=0; a<floatpt; a++)
{
aMean+=arr[a];
}
aMean=aMean/floatpt;
cout<<"Arithmetic Mean: "<<aMean<<endl;
}
void computeharmonicmean (double *arr, int floatpt, double hMean)
{
for (int h=0; h<floatpt; h++)
{
hMean+=(1/arr[h]);
}
hMean=floatpt/hMean;
cout<<"Harmonic Mean: "<<hMean<<endl;
}
void median(double *arr, int floatpt)
{
int temp;
double median;
for (int s=0; s<floatpt; s++)
{
for (int r=0; r<(floatpt-1); ++r)
{
if (arr[r] > arr[r+1])
{
temp = arr[r];
arr[r] = arr[r+1];
arr[r+1] = temp;
}
}
if (floatpt%2 == 0)
{
median = (arr[s/2] + arr[(s/2)-1])/2.0;
}
else
{
median = arr[s/2]/1.0;
}
}
cout<<"Median: "<<median<<endl;
}
void sort (double *arr, int floatpt)
{
cout<<"The sorted data set is: "<<endl;
for (int sd=0; sd<floatpt; sd++)
{
cout<<arr[sd]<<endl;
}
}
int count=0, floatpt;
double *arr =new double[count];
count is 0, so the array you create has no allocation. In getdata you therefore read into memory locations that are out of bounds.:
Did you intend to reallocate later?
Perhaps if you tried to use a std::vector<double>, then things would work out. It automatically resizes itself, and it's easy to do bounds checking.
Something like this (not tested):
#include <vector>
// ...
std::vector<double> data;
getdata(arr);
// ...
void getdata(std::vector<double>& arr)
{
double nextValue;
cout<<"Please enter floating point data.\n";
cout<<"After the last number has been entered press 0 (zero) \n";
cin>>nextValue;
while(nextValue != 0)
{
arr.push_back(nextValue);
cin >> nextValue;
}
}

C++ Data file with an unwanted character: How to remove rogue character and calculate mean, standard deviation and standard error

I have a data file which contains 49 numbers + 1 word and another file that contains 50 numbers. My task is to compute the mean, standard deviation and standard error for both. At the moment I have a code which will happily compute the correct values for the file containing only numbers. How do I remove the character?
I a beginner and unsure how to correctly use the getline() function to put data from the file into a string and then somehow use cin.ignore() and cin.clear() to remove the character? Help would be appreciated!
Program:
// Assignment 2: Milikan data programme
#include "stdafx.h"
#include<iostream>
#include<iomanip>
#include<fstream>
#include<cmath>
#include<string>
using namespace std;
//Mean function
double mean(double *mydata, double N)
{
double sum(0), m;
for (int i=0; i<N; i++)
{
sum += mydata[i];
}
m = (sum/(double)N);
return(m);
}
//Standard deviation function
double standard_dev(double *mydata, double m, int N)
{
double *mydata2 = new double[N];
for (int i=0; i<N; i++)
{
mydata2[i] = pow((mydata[i]-m), 2);
}
double sum(0), S, X;
for (int i=0; i<N; i++)
{
sum += mydata2[i];
}
X = sum/(N-1);
S = sqrt(X);
return (S);
}
int main ()
{
int N(0);
char filename[100];
double m, sterr, stdev;
string temp;
cout<<"Please enter the number of data points: ";
cin>> N;
cout<<"Please enter the name of the file: ";
cin>>filename;
//Dynamic memory allocation for N data points in array mydata
double *mydata;
mydata = new double[N];
//Open file and attach chosen file to myfile
ifstream myfile;
myfile.open(filename);
//Check it opened sucessfully
if(!myfile.is_open())
{
cerr<<"\nError: file could not be opened!"<<endl;
system("PAUSE");
return(1);
}
//Detect and ignore rogue character???
//Read data from the file into an array
for (int i=0; i<N; i++)
{
myfile>>mydata[i];
}
m = mean(mydata, N);
stdev = standard_dev(mydata, m, N);
sterr = 1/stdev;
cout<<"\nThe mean charge of an electron is : "<<m<<" eV"<<endl; /
cout<<"The standard deviation of results is : "<<stdev<<endl;
cout<<"The standard error of results is : "<<sterr<<endl;
myfile.close(); //Close file
delete[] mydata; // Free memory
system("PAUSE");
return 0;
}
Also remember that the stream objects failbit becomes set if the extraction of a number fails. You can check for that, and if set you skip all non-digit characters in the stream until you see a digit again.
Something like this pseudo code:
while (myfile)
{
myfile >> value;
if (myfile.fail())
{
clear_failbit();
while (next_character_is_not_digit())
get_and_discard_next_character();
}
}
Of course, a better solution would probably be to not generate files containing errors.

calculator in c++ adding function

So my program makes a random (x,y) arrays, what i want to do is to make x a real number and y imaginary number and add them:
my main program
#include "complx.h"
int main(){
const int n = 2;
Complex a[n];
getData(a,n);
printArray(a,n);
isort(a,n);
printArray(a,n);
complex_sum(a,n);
return 0;
}
it also prints and arranges the arrays, but what I am interested in is how to add the arrays, when for example I would use 4 arrays (x,y)(x,y)(x,y)(x,y).
this is how i get a random numbers
void getData(Complex a[],int n){
int i;
srand(time(0)); //If comment this out, get same sequence with each run.
for(i=0; i<n; i++){
a[i].x = rand()%3; //3 and 10 are just for testing isort
a[i].y = rand()%10;
}
return;
}
and here is how i'm trying to add it:
void complex_sum(Complex a[], int n){
for (int i=0; i<n; i++)
cout<<"("<<a[i].x+a[i].x<<")";
cout<<endl;
return;
I am stuck on how to add (x,y)(x,y)= x+yi
thanks
I am not completely inline with the way you are attempting; but to sum n number of complex numbers stored in an array and print it on screen you can try the following:
void complex_sum(Complex a[], int n){
int real=0,img=0;
for (int i=0; i<n; i++){
real+=a[i].x;
img+=a[i].y;
}
cout<<"("<<real << "+" << img << "i)";
}