# [Tutor] random number generator

Andrew James aijames at exemail.com.au
Sun Oct 7 03:52:51 CEST 2007

```I'm tempted to suggest using a hack to avoid floating point errors.

Anyway, it isn't choosing a number to ten decimal places. It's actually
out to 11 in both examples you gave. And it evaluates to correct because
your guesses were to at least 10 places, which is as far as you account
for in the line 'while (abs(number-guess) > 0.0000000001): '

Jim Hutchinson wrote:
> Greetings all,
>
> It seems I forgot to subscribe to the list so I didn't receive any of
> the replies. However, I did check the archive and found all of the
>
> Based on the replies I was able to get this to more or less work.
> However, one problem still exists. If you guess a number that is
> slightly larger than the random number it evaluates to correct
>
> For example:
>
> ----
> The number is 1.78889511441
> Make a guess: 1.788895114455
>
> Congratulations! You guessed my number! The number was 1.78889511441
>
> It took you only 1 tries!
> ---
>
> Or even:
>
> ---
> 1.36344601965
> Make a guess: 1.3634460196
>
> Congratulations! You guessed my number! The number was 1.36344601965
>
> It took you only 1 tries!
> ---
>
> I'm also unclear as to how it is choosing a random number out to 10
> decimal places. Is that the default and it's just coincidence that I
> chose 10? What if I want a random number to 20 decimal places or five?
>
> Here is the code:
>
> # Number guessing game
> #
> # The computer will choose a number between 1 and 2 (to ten decimal places)
> # and the player will try to guess the number. The program will tell the
> # player the number is either higher or lower than the number they guessed.
> import random
> import os
> os.system("clear")
> print "\nWelcome to 'Guess My Number'!"
> print "\nI'm thinking of a number between 1 and 2."
> print "\nYes, that's right. Between 1 and 2."
> print "\nYou have heard of decimals right? Well, I'm"
> print "\nthinking out to 10 decimal places. Good luck.\n"
> # set random value
> random.seed()
> number = random.random() + 1
> print number
> guess = float(raw_input("Make a guess: "))
> tries = 1
> # the guess loop
> while (abs(number-guess) > 0.0000000001):
>     if guess > number:
>         print "Lower..."
>     elif guess < number:
>         print "Higher..."
>     tries += 1
>     if guess != number:
>         guess = float(raw_input("Make another guess: "))
> print "\nCongratulations! You guessed my number! The number was", number
> print "\nIt took you only", tries, "tries!\n"
> # end
>
> Thanks again,
> Jim
>
```