In: Computer Science
Python program to simulate breaking a unit-length pencil into two places. Repeat the experiment 100,000 times and determine the average size of the smallest, middle-size, and the largest pieces. Record the estimate of the average sizes in your program
Please use comments to better explain what is happening in the code
Thanks for the question. Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks! =========================================================================== import random def main(): pencil_length = 1 smallest_length_total = 0 middle_size_length_total = 0 largest_size_length_total = 0 experiments = 100000 # loop 100000 times for experiment in range(experiments): break_p1 = random.random() # generate a random number 0 to 1, this is the first part remaining_length = pencil_length - break_p1 # pencil that remains break_p2 = random.random() * remaining_length # break the remaining pencil at random point first_part = break_p1 # this is the first part length second_part = break_p2 # this is the second part length third_part = remaining_length - break_p2 # this is the third part length lengths = [first_part, second_part, third_part] # to quick arrange the lengths in ascending order lengths.sort() # sort the lengths in ascending order smallest_length_total += lengths[0] # add the length to the total middle_size_length_total += lengths[1] # add the length to the total largest_size_length_total += lengths[2] # add the length to the total average_smallest = smallest_length_total / experiments # calculate teh average lengths average_middle = middle_size_length_total / experiments # calculate teh average lengths average_largest = largest_size_length_total / experiments # calculate teh average lengths print('Average length of smallest pieces:{:.5f}'.format(average_smallest)) # display print('Average length of middle pieces :{:.5f}'.format(average_middle)) print('Average length of largest pieces :{:.5f}'.format(average_largest)) if __name__ == '__main__': main()
======================================================================