views:

96

answers:

2

I would like to compute a weight as reciprocal of a distance for something like inverse distance weighting interpolation (http://en.wikipedia.org/wiki/Inverse_distance_weighting).

double wgt = 0, wgt_tmp, result = 0;
for (int i = 0; i < num; i++)
{
   wgt_tmp = 1.0/dist[i];
   wgt += wgt_tmp;
   result += wgt_tmp * values[i];
}
results /= wgt;

However the distance can be 0 and I need to make the weight suitable for computation. If there is only one distance dist[i] is 0, I would like its corresponding value values[i] to be dominant. If there are several distances are 0, I would like to have their values to contribute equally to the result. Also even if dist[i] is not zero but very small, I would like to have a reasonable criterion to check it and deal with it. Any idea how to implement it?

+3  A: 

Come up with definitions of "dominant", "very small" and "deal with it". Then, translate them into code.

Daniel Daranas
+1: I approve of general solutions. See my answer for an example or two.
Jefromi
+3  A: 

I don't see any way besides piecewise - you need a different function than reciprocal distance for small distances. The simplest thing would be to just chop off the top:

modified_dist[i] = dist[i] < MIN_DIST ? MIN_DIST : dist[i]

but you could replace that with something still decreasing if you want, like (MIN_DIST + dist[i])/2.

Jefromi
+1: A specific solution. It should be stressed that the choice is totally arbitrary. The question cannot be answered "objectively".
Daniel Daranas
Yup, very true. `MIN_DIST` provides a lot of flexibility, and the linear map can be fiddled with - a general form would be `(dist[i] - MIN_DIST) * k + MIN_DIST`, with `k < 1` but not so small that `dist[i] = 0` maps to something too small to divide by...
Jefromi
Thanks! Does it sound unreasonable if I set MIN_DIST=DBL_EPSILON and MAX_DIST=1.0/DBL_EPSILON when the problem context is not known beforehand?
Tim
I think you want to be a lot more conservative than that - you need wiggle room for all your later operations on `1/distance`. It'd really be best to have an idea of the context, too - in most situations, you can have a pretty good idea of a distance so small it doesn't matter. For example, why bother with a picometer cutoff when you're dealing with cars and a centimeter will do just fine?
Jefromi