import random
reiterations=1000
experiments=1000
headcount=0
tailcount=0
idealcount=0
nonidealcount=0
for i in range(1000):
for i in range(experiments):
for i in range(1000):
coin=bool(random.randint(0,1))
if coin==True:
tailcount =1
else:
headcount =1
if headcount==tailcount:
idealcount =1
else:
nonidealcount =1
print("Ideal outcomes:",idealcount)
print("Non-ideal outcomes:",nonidealcount)
So this is a rather simple piece of code, I was just a bit curious about the nature of probability and how it diverges when an outcome occurs so I decided to visualize that using a simple piece of code.
So just to explain what this does:
-It simulates a coin flip. (I know randint() isn't all that random, but hey it works!)
-And then it uses a for loop to repeat this simulation again and again.
for i in range(1000):
-It records the amount of heads and tails.
-And THEN it uses ANOTHER for loop to rerun the for loop to repeat the simulation again and again.
for i in range(experiments):
And I record the instances where the No. of Heads=No. Of Tails or in other words probabilistically ideal experiments and the instances where No. of Heads isn't equal to No. of Tails.
So far there's no problem, and this is the output I get: (Of course, since its based on randomness, the outcomes change every time I run it, like sometimes its 2,998 or 3,997.)
Ideal outcomes: 6
Non-ideal outcomes: 994
And I put all of this in ANOTHER for loop to see how the ideal outcomes vary and here's where the problem starts...
Ideal outcomes: 5
Non-ideal outcomes: 995
Ideal outcomes: 6
Non-ideal outcomes: 1994
Ideal outcomes: 6
Non-ideal outcomes: 2994
Ideal outcomes: 8
Non-ideal outcomes: 3992
Ideal outcomes: 8
Non-ideal outcomes: 4992
Ideal outcomes: 8
Non-ideal outcomes: 5992
Ideal outcomes: 9
Non-ideal outcomes: 6991
Ideal outcomes: 9
Non-ideal outcomes: 7991
Ideal outcomes: 9
Non-ideal outcomes: 8991
Ideal outcomes: 9
Non-ideal outcomes: 9991
Ideal outcomes: 9
Non-ideal outcomes: 10991
Ideal outcomes: 9
Non-ideal outcomes: 11991
Ideal outcomes: 9
Non-ideal outcomes: 12991
Ideal outcomes: 9
Non-ideal outcomes: 13991
Ideal outcomes: 9
Non-ideal outcomes: 14991
It does this weird thing, the non-ideal outcomes steadily increase by 1000.
I'm a beginner in python and as far as I see, there isn't any problem with this code, should be working fine but I have no idea why it's doing this.
Can somebody please explain to me what's going on here?
CodePudding user response:
For the outermost for loop, you want to reset the idealcount and nonidealcount numbers to zero. Otherwise, on every outer for loop iteration, you add the current idealcount to the previous one, causing that behavior that you see increases nonidealcount by around 1000 every time.