# How do I calculate the weighted least square

Get help using Construct 2

### » Mon Dec 15, 2014 1:15 am

Hey,

This one is for the math people...

How do I find the best 2d coordinate that minimizes the sum of the distances between a bunch of other points where each point is weighted to give it more or less value and these weights can be negative acting as repellant?

In other words, is it possible to calculate the best point on a gird that is the most optimized place to be given attractors and repellant coordinates?
B
34
S
11
G
2
Posts: 566
Reputation: 5,212

### » Mon Dec 15, 2014 1:24 am

not sure if this is exactly what you want but usually least squares refers to fitting a line/function to a dataset, which doesn't really match your request.

I think what you're after is more like the center of mass (c.o.m.), which is given by the relationship (positions are vectors, so you'd need to do this for x and y seperately)

(total mass) * (position vector of c.o.m.) = mass1*position1+mass2*position2+....massN*positionN

you can solve for the center of mass (c.o.m.) position by dividing the right hand side by the total mass. masses act as your "weighting" and theres no reason you can't give them a negative value, although the effect may be different than what you're looking for, i'm not sure how else you'd define the effect of a negative weighting in something like this.
B
79
S
13
G
8
Posts: 1,977
Reputation: 9,947

### » Mon Dec 15, 2014 2:31 am

Sounds a little like a boids type of scenario.
Average the axes sorta like quasi was saying.
x1+x2+etc/ number of instances, same for y
B
173
S
50
G
194
Posts: 8,570
Reputation: 121,376

### » Mon Dec 15, 2014 12:08 pm

let's say you have

O (0,0) <-- starting point on X,Y coordinate system, and let's say you have
A (1,1)
B (-1,-1) points

Now IF we check the midpoint for these 2 points it's clearly startPoint(0,0) because it's on the center of it.
But if i understand you correctly - you have A(1,1,5) and B(-1,1,10) where the 3rd number is "weight", meaning that higher value is better, lower is worse - > then we clearly see that B has 2x better value.
Meaning that our spot that we are looking for is going to be startPoint(-0.25,-0,25) (correct me someone if i'm wrong) - > so you pick up that formula and extend it for N points and there you go.

an idea just popped out - sum up all the weights then divide with number of points, then calculate the weighted value - (avg * weight) and you should get their "real" values. should be easier to work with that. also i think you should have weights only > 0, for ease of computation. <0 could cause problems.
Sea Monsters template - Isometric
Also includes 40 pages PDF of optimizations and "how-to" for your games, and how the "sea monsters" template was built. Follow link for details :)

sea-monsters-templates-and-assets_t162705
B
43
S
14
G
12
Posts: 627
Reputation: 9,457