Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best algorithm for converting real number between 0 and 1 to index

Suppose x is a real number between 0 and 1

If n = 2 there are two fractions ranges 0 to 0.5 and 0.5 to 1

If n = 3 there are three fractions ranges 0 to 0.33, 0.33 to 0.66 and 0.66 to 1

I want to know the most efficient algorithm that tells which fraction x belongs to.

If x = 0.2 and n = 3, x belongs to first fraction so index is 0

If x = 0.4 and n = 3, x belongs to second fraction so index is 1

Here's the python 3 code which has O(N) complexity.

def index(x, n):
  for i in range(0, n):
    if i/n <= x and x <= (i + 1)/n:
      return i

I want to know if there is a better algorithm may be with constant time?

Edit: I did not explicitly said before but both 0 and 1 is a legit value for x and result should be n - 1 when x = 1

like image 713
chamoda Avatar asked Jan 02 '23 16:01

chamoda


1 Answers

Just multiply both numbers and cut the decimal place:

def index(x, n):
    return int(x*n)

Complexity is O(1)

like image 71
miindlek Avatar answered Jan 05 '23 05:01

miindlek