# How do I calculate the weighted least square

• 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?

• 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.

• 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

• ## Try Construct 3

Develop games in your browser. Powerful, performant & highly capable.

Construct 3 users don't see these ads
• 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.