ValueError; low >= high

Question:

I am getting "low >= high" error in the loop code below, how can it be resolved?

while True:
    max_num = 1000
    num_1 = np.random.randint(1, max_num)
    num_2 = np.random.randint(1, max_num)

    if (num_1 < num_2):
        num_2 = np.random.randint(1, num_1)
    break
Asked By: Emir

||

Answers:

In your condition:

if (num_1 < num_2):
      num_2 = np.random.randint(1, num_1)

num_1 can equal to 1. In this case this np.random.randint(1, num_1) gives the error, as the low and the high integers are equal.

Answered By: Franciska

Your while loop is pointless currently since it will always break on the first iteration.

Since you seem to want two random numbers, where num_1 >= num_2, a simple fix would be just:

max_num = 1000
while True:
    num_1 = np.random.randint(1, max_num)
    num_2 = np.random.randint(1, max_num)

    if (num_1 >= num_2):
        break

This will keep looping, picking fresh pairs of random numbers, until the desired condition (num_1 >= num_2) is met.

Answered By: Anentropic
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.