[Tutor] Unexpected Result in Test Sequence
Tim Peters
tim.peters at gmail.com
Mon Nov 16 20:44:57 CET 2009
[kb1pkl at aim.com]
> I'm running a test to find what the experimental average of a d20 is,
I don't know what "a d20" is, but your code is picking integers
uniformly at random between 1 and 18 inclusive. The expected value is
therefore (1+18)/2.0 = 9.5.
> and came across a strange bug in my code.
>
> import random
> list1 = []
Note that you never clear this list. It just keeps growing, and
growing, and growing ...
> def p():
> d = 0
> for number in range(1,1000):
> t = random.randrange(1,19)
> list1.append(t)
On average, the sum of the 1000 integers you just added is 9.5 * 1000 = 9500.
> for value in list1:
> d+=value
So the sum of the entire list (which you never clear) will be
approximately 9500 times the number of times you've called p().
> print d/1000
Here you're dividing by 1000 no matter how long the list is, The
first time you call p(), it does have 1000 integers by the time you
get here. The second time you call p(), it will have 2000 integers by
the time you get here. And so on. So what I expect this to print is
approximately
9500 * the number of times you've called p() / 1000 =
approximately 9.5 times the number of times you've called p()
However, you're using truncating integer division, not floating
division, so the truth of that is obscured.
> d = 0
This line didn't do anything for you.
> for value in range(1,100):
> p()
>
> It works, but I have a logic error somewhere. It runs, and the results have
> a pattern :
> 9
As above, approximately 9.5 times 1.
> 19
Approximately 9.5 times 2.
> 28
Approximately 9.5 times 3.
> 37
Approximately 9.5 times 4.
> 47
> 56
> 66
> 75
> 85
> 94
> 104
> 113
> ...
Etc.
> It just adds 10, and every second result, subtracts 1, till it gets to 0,
> and then starts again with 9 in singles, and whatever in the 10's, etc.
> What is causing this?
A couple things: you're never clearing list1, and you're using
truncating integer division to compute the average. I /suspect/ you
didn't really intend "randrange(1, 19)" either, but that depends on
what "a d20" means.
Try this instead ;-)
import random
def p():
list1 = [random.randrange(1, 19) for dummy in xrange(1000)]
print float(sum(list1)) / len(list1)
for value in range(1,100):
p()
More information about the Tutor
mailing list