0

I have an array of rational numbers, say A=[1.5 2.8 3.5 4.8 5.9 6.5 7.6 8.3 9.1 10.7]

How do I find that a given number, say B=5.6 is closer to 5.9(in the array A.

I want to code this in python.

Can somebody please let me know on how do we go about solving this?

Ranjan Pal
  • 307
  • 3
  • 13

1 Answers1

1

A solution can be like this :


A=[1.5, 2.8, 3.5, 4.8, 5.9, 6.5, 7.6, 8.3, 9.1, 10.7]

target = 5.6

closest = min(A)

diff = 10000000


for a in A:
    if abs(a-target) <= diff:
        closest = a
        diff = abs(a-target)


print("closest to ", target , ' is ', closest)