[Tutor] Unexpected Result in Test Sequence
vinces1979 at gmail.com
Mon Nov 16 20:42:08 CET 2009
On Mon, Nov 16, 2009 at 1:18 PM, <kb1pkl at aim.com> wrote:
> Hello Tutor list.
> I'm running a test to find what the experimental average of a d20 is, and
> came across a strange bug in my code.
> import random
> list1 = 
> def p():
> d = 0
> for number in range(1,1000):
> t = random.randrange(1,19)
> for value in list1:
> print d/1000
> d = 0
> for value in range(1,100):
> It works, but I have a logic error somewhere. It runs, and the results have
> a pattern :
> 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?
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
I think that one problem you are seeing is caused by the use of integers
When you are dividing sum of the random number by 1000, python is rounding
Also your list, never gets cleared and you keep adding to the original list,
and you are then dividing by the original 1000
A simple fix is to use floats (PS: cleaned up a bit):
from random import randrange
mylist = [randrange(1,19) for x in range(1, 1000)]
d = sum(list)
print float(d) / len(mylist)
for value in range(1,100):
Hope this point you in a better direction
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Tutor