Monte Carlo simulation to calculate PI
Source code name: "guessing_pi.py"
Programming language: Python
Topic: Histograms/2D
DMelt Version 1.4. Last modified: 07/18/1971. License: Pro
https://datamelt.org/code/cache/guessing_pi_6042.py
To run this script using the DMelt IDE, copy the above URL link to the menu [File]→[Read script from URL] of the DMelt IDE.


from java.util import Random
from java.lang import Math
from jhplot import *

h1 = H2D("PI",100,0.0,1.0,100,0.0,1.0)

nThrows=0
nSuccess=0
for i in range(1000000):
 x,y=Math.random(),Math.random()
 nThrows=nThrows+1
 if (x*x+y*y<=1):
              nSuccess=nSuccess+1;
              h1.fill(x,y)

c1 = HPlot3D("Canvas",600,600)
c1.visible()
c1.setNameX("X")
c1.setNameY("Y")
c1.setRangeZ(0,20)
c1.setDensity()
c1.draw(h1)

guesssed=4*nSuccess/float(nThrows)
print "Pi/4=",nSuccess/float(nThrows)
print "Pi=",guesssed
print "Actual Pi=",Math.PI
print "Difference=",(1-guesssed / Math.PI)*100



You see the box below because you did not login.