Python Forum
Some help with python code
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Some help with python code
#1
Hey guys,
I am trying to improve upon a Buffon Needle Simulation. Basically, what I need is code that would require me to select an amount of needles to 'drop' (X) and give me the value of 'hits' on the surface lines, and repeat the process N times (trials) and since each trial gives different values of hits, I want it to generate the mean hit value automatically from the N trials. So far, I have managed to loop the code in order to provide me with the different number of hits based upon the number of trials. But now I am confused on how to automatically generate the mean of the values shown. I tried using an average function but it didn't work. The code is as follows:
print "Hit list"

for hit in range(3): #number of trials
  import math
  import random
  
  hit = 0
  total = 0
  deg = random.randint(0,180)
  pos_mid = random.randint(2000,8000) / 1000
  pos_bot = pos_mid - (math.sin(math.radians(deg)) / 2)
  pos_top = pos_mid + (math.sin(math.radians(deg)) / 2) 
  acc = 100 #number of needles thrown
  
  while total < acc:
  	if pos_bot % 2 == 0 or pos_top % 2 == 0:
  		hit += 1
  	elif pos_bot < 2 and pos_top > 2:
  		hit += 1
  	elif pos_bot < 4 and pos_top > 4:
  		hit += 1
  	elif pos_bot < 6 and pos_top > 6:
  		hit += 1
  	elif pos_bot < 8 and pos_top > 8:
  		hit += 1
  	else :
  		hit = hit
  	total += 1
  	deg = random.randint(0,180)
  	pos_mid = random.randint(2000,8000) / 1000
  	pos_bot = pos_mid - (math.sin(math.radians(deg)) / 2)
  	pos_top = pos_mid + (math.sin(math.radians(deg)) / 2) 
  if hit == 0:
  	print ("0")
  else:
  	print (hit) #needles that intersect the lines

print "Average"  
x = [hit]
print (x)
avg = sum (x) / len(x)
print (avg)
Help would be greatly appreciated
Reply
#2
Based on your print statement on line 38, you are using Python 2.x. The default division in 2.x is integer division, which truncates the result. You either need this at the top of your file (it must be the first line of code):

from __future__ import division
or you need to change your average calculation to:

avg = sum(x) / float(len(x))
That's what I get from glancing at your code. If you are having other problems, please clearly state how the output is incorrect, or give the full text of the error you are getting.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020