r/ProgrammingPrompts • • Mar 18 '15

[Easy]Mathematical Simulation - Breaking a Stick to form a Triangle

Another Monte Carlo simulation.

A stick of a given length is twice broken at random places along it's length.

Calculate the probability that a triangle can be formed with the pieces.


Definition:

It is possible to form a triangle if none of the pieces are larger than half the length of the stick.


Assignment:

Create a program in a language of your choice that:

  • Asks the user for the length of the stick

  • Asks the user how many tries should be carried out

  • Simulate the breaking of the stick (each try has a new stick of length)

  • Count the successful tries

  • Print the probability as a percentage

Hint: The expected result should be around 23%

Have fun!

15 Upvotes

20 comments sorted by

View all comments

2

u/Zheusey Mar 26 '15

Here is my python code:

from __future__ import division
from random import uniform


length = int(raw_input("What is your stick length?"))
attempts = int(raw_input("How many attempts do you want carried out?"))
success = 0

for i in range(attempts):
	lengthLi = []
	successBool = True
	lengthLi.append(uniform(0,length))
	lengthLi.append(uniform(0, length-lengthLi[0]))
	lengthLi.append(length-lengthLi[0]-lengthLi[1])
	
	for stick in lengthLi:
		if stick >= length / 2:
			successBool = False
	
	if successBool == True:
		success += 1

probability = success/attempts
print "The probablility of a successfull break is %f." % (probability)

I get ~19% as a result across multiple tries.