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 Rhoades

GPO Box 3411
Sydney NSW 2001
Australia
E-mail: phil@pricom.com.au

Philip Rhoades 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]}

···

--
Posted via http://www.ruby-forum.com/\.

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

···

On Fri, Jul 15, 2011 at 12:52 PM, 7stud -- <bbxx789_05ss@yahoo.com> wrote:

Philip Rhoades 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]}

--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/