# C++ performance: Linear regression in other way

Here is the code that can be used for calculation of mathematical function, like `ax^2 + bx + c`.

It is fast enough if you choose small length, otherwise if programmer don’t know the small range, that code can be really slow. I’ve made it specially on C++ to be more fast.

``````#include <iostream>
#include <vector>

using namespace std;

template<class var>
var Module(var x){
if (x >= 0)
return x;
else
return x*-1;
}

class Linear {
public:
float resA, resB, resC;
float err;

float Predict(float a, float b, float c, float x) {
return ((a * (x*x)) + (b*x) + c);
}

float Predict(float x) {
return ((resA * (x * x)) + (resB * x) + resC);
}

float ErrorAv(float a, float b, float c, vector<float> input, vector<float> output) {
float error = Module(Predict(a, b, c, input(0)) - output(0));
for (int i = 1; i < input.size(); i++)
error = (Module(Predict(a, b, c, input(i)) - output(i)) + error)/2;
return error;
}

void LinearRegr(vector<float> input, vector<float> output, float maximum, float minimum = 0, float step = 1) {
if (step == 0)
step++;
float a, b, c;

float lastError = INFINITY;
for (a = minimum; a <= maximum; a += step)
for (b = minimum; b <= maximum; b += step)
for (c = minimum; c <= maximum; c += step) {
float error = ErrorAv(a, b, c, input, output);
if (error < lastError) {
lastError = error;
resA = a;
resB = b;
resC = c;
err = lastError;

if (!lastError)
return;
}
}

}
};

#include <ctime>
int main(){
vector<float> input; //Input example.
vector<float> output; //Output example.

float a = 10.5, b = -7, c = 5.5; //Variables as search values.

//Fill dataset:
for (int i = 0; i < 100; i++) {
input.push_back(i);
output.push_back((a * (i * i)) + (b * i) + c);
}

clock_t begin = clock(); //Start clock while searching a, b, c values
Linear linear;
linear.LinearRegr(input, output, 15, -10, 0.5); //Start searching.
cout << "Time: ~" << double(clock() - begin) / CLOCKS_PER_SEC << " seconds." << endl;

cout << linear.resA << "*x^2 + " << linear.resB << "x + " << linear.resC << endl; //Enter results.
}
``````

As can see, `Linear.LinearRegr` function can get from 3 to 5 parameters.
I dont need make the code super prettier(for me its already pretty), just want to work it faster.

How to optimize and make it faster?