Samasha
Samasha

Reputation: 469

Find the nearest value in an array to the given value

I want to retrieve the nearest value from the array list for the given value.

I tried to retrieve the nearest value, but I'm having trouble with the for loop I am using.

def get_total_price_iot(self):
    """calculate the price """


    value = 2.5
    constants = [2,3,4,5]

    for x in range(len(constants)):
      if(value<constants[0]):
           print('Nearest Value ',constants[0])

      elif(value>=constants[x] and value<=constants[x+1]):
          midValue = (constants[x] + constants[x + 1]) / 2

          if (midValue <= value):
              midValue = constants[x + 1];
              print("Nearest midGirth ", midValue)
          elif (midValue > value):
              midValue = constants[x]
              print("Nearest value ", midValue)


      else:
          print('Nearest value ',constants[len(constants)-1])

My expected result is 3, but I'm getting 4 as output instead.

Here is my output:

Nearest midGirth  3
Nearest value  5
Nearest value  5
Nearest value  5

Upvotes: 0

Views: 112

Answers (4)

Mark
Mark

Reputation: 92461

You can just find the min of the difference using the key of the min function. In the case of ties Python 3's min() will return the first value encountered. Since your constants are sorted you can look through them in reverse to get the effect of rounding up:

value = 2.5
constants = [2,3,4,5]

# find the min of the differences between value and constants
# ties will find the largest value
min(reversed(constants), key = lambda x: abs(x-value))

# Result:  3

Upvotes: 1

Devesh Kumar Singh
Devesh Kumar Singh

Reputation: 20500

If you are guaranteed that the input list is an integer, just convert value to it's ceiling by math.ceil and compare number with value

import math

value = 2.5
constants = [2,3,4,5]

for item in constants:
    if item == math.ceil(value):
        print(item)

The answer will be 3 here

An optimized approach is to calculate a difference array, i.e. difference between value and each element, sort it and return the 2nd element+value

def get_nearest(value, constants):

    #Calculate the difference array between value and each element in constants
    diffs = [item-value for item in constants]

    #Sort it
    diffs = sorted(diffs)

    #Return the second element+value
    return diffs[1]+value

The outputs will be

print(get_nearest(2.5, [2,3,4,5]))
#3.0
print(get_nearest(2.5, [2,13,4,5]))
#4.0
print(get_nearest(2.1, [2,13,4,5]))
#4.0

Upvotes: 2

alexprice
alexprice

Reputation: 404

use numpy:

import numpy as np
a=np.array([2,3,4,5])
a[np.abs((a-value)).argmin()]

it will outpout 2 for value=2.5 because it's standard rounding. if you need nonstandard 2.5->3 rounding round value using decimals module

Upvotes: 0

R4444
R4444

Reputation: 2114

If I understand your question correct, you want to do something like this:

value = 2.5
constants = [2,3,4,5]

for x in range(len(constants)):
  if(value<constants[0]):
       print('Nearest Value ',constants[0])
       break

  elif(value>=constants[x] and value<=constants[x+1]):
      midValue = (constants[x] + constants[x + 1]) / 2

      if (midValue <= value):
          midValue = constants[x + 1];
          print("Nearest midGirth ", midValue)
          break
      elif (midValue > value):
          midValue = constants[x]
          print("Nearest value ", midValue)
          break
  else:
      print('Nearest value ',constants[len(constants)-1])
      break

Notice I am using breaks in between.

Output:

Nearest midGirth  3

Also I am confused with:

But I'm getting 4 output. I want to avoid it

I guess you want to display only: Nearest midGirth 3.

Upvotes: 1

Related Questions