Skip to content

Instantly share code, notes, and snippets.

@stevenklise
Created May 21, 2013 22:00
Show Gist options
  • Save stevenklise/5623628 to your computer and use it in GitHub Desktop.
Save stevenklise/5623628 to your computer and use it in GitHub Desktop.
PVector[] vectors = {leftHand, rightHand, leftElbow, rightElbow, leftShoulder, rightShoulder};
// returns m and b as 0 and 1 of an array respectively.
float[] fits = bestFit(vectors);
// this value is floating all over the place
float r2 = rsquare(vectors, fits[0], fits[1]);
float rsquare(PVector[] list, float m, float b) {
float average = 0.0;
for (PVector vector : list) {
average += vector.y;
}
average = average / (float)list.length;
float sumtot = 0;
float sumerr = 0;
float sumreg = 0;
for (PVector vector : list) {
sumtot += pow(vector.y - average, 2);
sumerr += pow(vector.y - vector.x * m + b, 2);
sumreg += pow(vector.x * m + b - average, 2);
}
return 1 - sumerr / sumtot;
}
// Take a list of PVectors and calculate the slope and y-intercept
float[] bestFit(PVector[] list) {
float n = (float)list.length;
float m = 0;
float b = 0;
float sumproduct = 0;
float sumx = 0;
float sumx2 = 0;
float sumy = 0;
for (PVector v : list) {
sumx += v.x;
sumx2 += pow(v.x,2);
sumy += v.y;
sumproduct += v.x * v.y;
}
m = (sumproduct - (sumx * sumy / n)) / (sumx2 - pow(sumx,2)/n);
b = sumy / n - m * sumx / n;
float[] response = {m, b};
return response;
}
@sklise
Copy link

sklise commented Dec 11, 2019

Hello

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment