Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
| Download

All published worksheets from http://sagenb.org

Views: 168733
Image: ubuntu2004
### This script estimates pi by shooting randomly at a circle inscribed in a square var ('x y r n') r = 1 n = 100 points = [] inside = 0 ### Shoot randomly into the square: for i in range(0,n): [x,y]=[random(),random()] points.append([x,y]) ### If a shot lands inside the circle, make a note of it if (y <= sqrt((r^2)-(x^2))): inside += 1 ### Approximate pi based on the fraction of shots that landed in the circle ### Area of circle = pi*r^2 ### Area of square = (2*r)^2 = 4*r^2 ### Shots in circle / Shots in square = (pi*r^2)/(4*r^20 = pi()/4 piapprox = 4*(inside / n) estimate = "Based on " estimate += str(n) estimate += " shots, pi is ~= " estimate += str(piapprox.n()) show(estimate) ### Graph the solution circle = [] for i in range(0,1000): x = i/1000 y = sqrt((r^2)-(i/1000)^2) circle.append([x,y]) graph = list_plot(points) graph += list_plot(circle,color='red',figsize=[6,4],plotjoined=true) show(graph)
Basedxonx100xshots,xpixisx~=x3.04000000000000\renewcommand{\Bold}[1]{\mathbf{#1}}\verb|Based|\phantom{\verb!x!}\verb|on|\phantom{\verb!x!}\verb|100|\phantom{\verb!x!}\verb|shots,|\phantom{\verb!x!}\verb|pi|\phantom{\verb!x!}\verb|is|\phantom{\verb!x!}\verb|~=|\phantom{\verb!x!}\verb|3.04000000000000|