# Elegant selection of closest number?

People,

Say I have numbers: 0.1 0.2 0.3 0.4 0.5

then I want to process thousands of numbers, choosing which of the
above numbers the processed number is closest to. I can see ways of
doing this eg I could calculate mid-points of the above numbers and then
iterate through that list checking the value of |x - mid-point| to find
the minimum value but I think there should be a more elegant, direct
method but I can’t think of it. Suggestions?

Thanks,

## Phil.

Philip R.

GPO Box 3411
Sydney NSW 2001
Australia
E-mail: [email protected]

Philip R. wrote in post #1010919:

People,

buckets = [
0.1,
0.2,
0.3,
0.4,
0.5,
]

data = [
0.00,
0.14,
0.19,
0.24,
0.25,
0.41,
1.00,
]

results = Hash.new {|hash, key| hash[key] = []}

data.each do |num|
rounded = num.round(1)

first = buckets.first
last = buckets.last

if rounded < first
results[first] << num
elsif rounded > last
results[last] << num
else
results[rounded] << num
end
end

p results

–output:–
{0.1=>[0.0, 0.14], 0.2=>[0.19, 0.24], 0.3=>[0.25], 0.4=>[0.41],
0.5=>[1.0]}

On Fri, Jul 15, 2011 at 12:52 PM, 7stud – [email protected]
wrote:

results = Hash.new {|hash, key| hash[key] = []}
results[last] << num
else
results[rounded] << num
end
end

p results

–output:–
{0.1=>[0.0, 0.14], 0.2=>[0.19, 0.24], 0.3=>[0.25], 0.4=>[0.41],
0.5=>[1.0]}

buckets and data as above

buckets.sort!

result = data.group_by do |x|
delta = nil
buck = nil

buckets.each do |b|
d = (x - b).abs
break if delta && d > delta
delta = d
buck = b
end

buck
end

Kind regards

robert