-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsketch.js
74 lines (73 loc) · 1.53 KB
/
sketch.js
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
let p = [];
let m, b;
let xsum = 0,
ysum = 0;
let btn;
function setup() {
createCanvas(windowWidth, windowHeight);
btn = createButton("Reset")
.position(10, 10)
.mouseReleased(() => {
p = [];
xsum = 0;
ysum = 0;
});
}
function draw() {
background(30);
stroke(255);
strokeWeight(5);
for (let i = 0; i < p.length; i++) {
let yy = map(p[i].y, 0, height, height, 0);
point(p[i].x, yy);
}
if (p.length > 1) {
linearRegression();
}
noStroke();
fill(200);
textSize(25);
textAlign(CENTER, CENTER);
text("Linear Regression", width / 2, 20);
textSize(15);
fill(150);
text("Click to add points ", width / 2, 50);
}
function mouseReleased() {
if (
!(mouseX > btn.position().x &&
mouseX < btn.position().x + btn.width &&
mouseY > btn.position().y &&
mouseY < btn.position().y + btn.height)
) {
let yy = map(mouseY, 0, height, height, 0);
p.push({ x: mouseX, y: yy });
xsum += mouseX;
ysum += yy;
}
}
function drawline() {
let x1 = 0;
let y1 = m * x1 + b;
let x2 = width;
let y2 = m * x2 + b;
y1 = map(y1, 0, height, height, 0);
y2 = map(y2, 0, height, height, 0);
stroke(50, 55, 250);
strokeWeight(2);
line(x1, y1, x2, y2);
}
function linearRegression() {
let n = p.length;
let xMean = xsum / n;
let yMean = ysum / n;
let up = 0;
let down = 0;
for (let i = 0; i < n; i++) {
up += (p[i].x - xMean) * (p[i].y - yMean);
down += (p[i].x - xMean) * (p[i].x - xMean);
}
m = up / down;
b = yMean - m * xMean;
drawline();
}