Dawson Kern
Dawson Kern

Reputation: 21

Why does this program work when the "guess" number is randomly generated, but not when it's based on the average of the upper and lower bound?

I was writing code in Python to simulate a guessing game, where one person picks a random number in a certain range and another person has to guess it. The first person will tell the second person if their guess is too high or too low. I tried to find the average number of guesses it will take for certain upper bounds on the randomly picked numbers (I kept the lower bound consistent at 1). I set two "strategies" for the second player to use: one where they pick random numbers between the upper and lower bounds set by previous guesses, and one where they always guess the average of the two bounds.

I originally didn't add the round() function on the random guessing, but I thought I could fix the problem by adding it. I also set my computer to output the difference between the guess and the actual number to see what was going wrong.

while right==0:
    #the two methods of guessing
    if o==1:
        guess=random.randint(x,y)
    if o==2:
        guess=int(round((x+y)/2))
    if guess<number:
        #sets lower bound as the guess if the guess is too low
        x=guess
    elif guess>number:
        #sets upper bound as the guess if the guess is too high
        y=guess
    else:
        right=1

I expected both methods to be able to calculate the result, and they could, for smaller numbers. However, when I tried to calculate the average number of guesses for a randomly picked number 1 to a googol, the first method worked, but the second one didn't. When I set my computer to output the difference between the guess and the actual number, I expected it to get smaller and smaller until it reached 0 (the two numbers were equal). That happened with the first method, but when I tried it with the second method, the guess always stopped at a certain number. I output the difference between the guess and the number three times, and these were the three numbers it stopped at:

-872708632555842351491581711811827543535535573132668221579096061472556190196974407542

450599818234666564246053810455950002658663408825326497921624797530090552669446353142

49016676324222343388551228825274910790413155248002458659403784218988029381383159387

Upvotes: 1

Views: 124

Answers (1)

Juan Carlos Ramirez
Juan Carlos Ramirez

Reputation: 2129

Not all integers can be represented as floating point numbers. The gap between one floating point number and the next is not fixed, but grows as the magnitude of you floating point grows. This means that for large enough floating point fx, next(fx)-fx>2 and so you will be left with an integer in the interval from fx to next(fx) that will not be represented. enter image description here

Upvotes: 0

Related Questions