LeastSquares

Hi, everyone. I am trying to calculate slope and intercept (y=mx+b) of 37 data files in .txt files I have. Can anyone tell me if I'm going about this right?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>
#include <cstdlib>
#include <fstream>

using namespace std;

int main(int argc, char**argv)
{
    ifstream fFile, cFile;
    fFile.open("DegreeF_X.txt");
    cFile.open("DegreeC_Y.txt");
    
    double fData [37];
    double cData [37];
    
    for (int i = 0; i < 37; i++)
    {
        fFile >> fData[i];
        cFile >> cData[i];
    }
    
    double Sx, Sy, Sxy, Sx2;
    double N = 37;
    
    for (int i = 0; i < 37; i++)
    {
        Sx += fData[i];
        Sy += cData[i];
        Sxy += fData[i]*cData[i];
        Sx2 += fData[i]*fData[i];
    }
    
    double m, b;
    
    m = (Sxy-((Sx * Sy)/N)) / (Sx2 - ((Sx*Sx)/N));
    b = (Sy - (m * Sx))/N;
    
    cout << m << endl << b;
    
    return 0;
}
@gainzbro

I can't test your program, as I don't have the data files, but I do see one error. Line 22. You've declared your variables but neglected to assign a value. Lines 27 thru 30 are taking the unknown start values of Sx, Sy, Sxy and Sx2, and adding them to your array values. You should start each of your declared values in line 22 as 0.0

Here are my values for DegreeF_X.txt file:

32
37
42
47
52
57
62
67
72
77
82
87
92
97
102
107
112
117
122
127
132
137
142
147
152
157
162
167
172
177
182
187
192
197
202
207
212

and here are the values for my DegreeC_Y.txt file:

0.01
2.54
5.97
8.00
10.35
14.61
16.61
18.86
22.80
25.41
27.11
31.21
32.35
36.39
38.34
41.81
43.99
46.94
49.06
53.08
55.12
59.10
62.00
62.94
65.77
70.17
72.52
75.84
78.11
80.82
83.69
86.81
89.11
91.46
93.58
96.74
99.64

To assign values to my variables in line 22, would I set it as:

double Sx = 0.0, Sy = 0.0, ... ?
@gainzbro

To assign values to my variables in line 22, would I set it as:

double Sx = 0.0, Sy = 0.0, ... ?


Yes, that is right.

Also, on line 23, you could declare N as in int. It doesn't change the way the program runs or change the output, but using a double, isn't really necessary.

I ran the program with your data files, and ended up with m = 0.55606 and b equaling -17.8702.

Is that what you get as well??
Last edited on
Topic archived. No new replies allowed.