Is there an elegant method to create a number that does not exist in a given list of floating point numbers? It would be nice if this number were not close to the existing values in the array.
For example, in the list [-1.5, 1e+38, -1e38, 1e-12] it might be nice to pick a number like 20 that’s “far” away from the existing numbers as opposed to 0.0 which is not in the list, but very close to 1e-12.
The only algorithm I’ve been able to come up with involves creating a random number and testing to see if it is not in the array. If so, regenerate. Is there a better deterministic approach?
If you have the constraint, that the new value must be somewhere in between
[min, max]then you could sort your values and insert the mean value of the two adjacent values with the largest absolute difference.In your sample case
[-1e38, -1.5, 1e-12, 1e+38]is the ordered list. As you calculate the absolute differences, you’ll find the maximum difference for the values(1e-12, 1e+38)so you calculate the new value to be((n[i+1] - n[i]) / 2) + n[i](simple mean value calculation).Update:
Additionally you could also check if the
FLOAT_MAXorFLOAT_MINvalues will give good candidates. Simply check their distance tominandmaxand if the result values are larger than the maximum difference for two adjacent values, pick them.