Monte Carlo methods: Difference between revisions
Content added Content deleted
m (→{{header|REXX}}: added/changed whitespace and comments.) |
|||
Line 2,119: | Line 2,119: | ||
A specific-purpose commatizer function is included to format the number of iterations. |
A specific-purpose commatizer function is included to format the number of iterations. |
||
<lang rexx>/*REXX program computes and displays the value of pi÷4 using the Monte Carlo algorithm*/ |
<lang rexx>/*REXX program computes and displays the value of pi÷4 using the Monte Carlo algorithm*/ |
||
⚫ | |||
⚫ | |||
parse arg times chunk digs r? . /*does user want a specific number? */ |
|||
⚫ | |||
if chunk=='' | chunk=="," then chunk= 100000 /*perform Monte Carlo in 100k chunks.*/ |
|||
if digs =='' | digs=="," then digs= 99 /*indicates to use length of PI - 1. */ |
|||
if datatype(r?, 'W') then call random ,,r? /*Is there a random seed? Then use it.*/ |
|||
⚫ | |||
⚫ | |||
pi= strip( left(pi, digs + length(.) ) ) /*obtain length of pi to what's wanted.*/ |
|||
numeric digits length(pi) - 1 /*define decimal digits as length PI -1*/ |
|||
say ' 1 2 3 4 5 6 7 ' |
say ' 1 2 3 4 5 6 7 ' |
||
say 'scale: 1·234567890123456789012345678901234567890123456789012345678901234567890123' |
say 'scale: 1·234567890123456789012345678901234567890123456789012345678901234567890123' |
||
say /* [↑] a |
say /* [↑] a two─line scale for showing pi*/ |
||
say 'true pi= ' pi"+" /*we might as well brag about true pi.*/ |
say 'true pi= ' pi"+" /*we might as well brag about true pi.*/ |
||
say /*display a blank line for separation. */ |
|||
limit = 10000 - 1 /*REXX random generates only integers. */ |
|||
⚫ | |||
⚫ | |||
accuracy= 0 /*accuracy of Monte Carlo pi (so far).*/ |
|||
⚫ | |||
⚫ | |||
!= 0 /*!: is the accuracy of pi (so far). */ |
|||
do j=1 for times % chunk |
|||
⚫ | |||
⚫ | |||
⚫ | |||
if random(, limit)**2 + random(, limit)**2 <= limitSq then != ! + 1 |
|||
end /*chunk*/ |
|||
reps= chunk * j /*calculate the number of repetitions. */ |
|||
_= compare(4*! / reps, pi) /*compare apples and ··· crabapples. */ |
|||
if _<=accuracy then iterate /*Not better accuracy? Keep truckin'. */ |
|||
⚫ | |||
⚫ | |||
accuracy= _ /*use this accuracy for next baseline. */ |
|||
⚫ | |||
if _<=accuracy then iterate /*Not better accuracy? Keep truckin'. */ |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
/*──────────────────────────────────────────────────────────────────────────────────────*/ |
/*──────────────────────────────────────────────────────────────────────────────────────*/ |
||
commas: procedure; arg _; do k=length(_)-3 to 1 by -3; _=insert(',',_,k); end; return _</lang> |
|||
{{out|output|text= when using the default input:}} |
{{out|output|text= when using the default input:}} |
||
<pre> |
<pre> |