Monte Carlo methods: Difference between revisions

Content added Content deleted
m ((Dialects of BASIC moved to the BASIC section.))
(Monte Carlo methods in various BASIC dialents (BASIC256, Run BASIC, True BASIC and Yabasic))
Line 416: Line 416:
40000 3.1452
40000 3.1452
</pre>
</pre>

====Other solution:====
<syntaxhighlight lang="freebasic">print " Number of throws Ratio (Pi) Error"

for pow = 2 to 8
n = 10 ^ pow
pi_ = getPi(n)
error_ = 3.141592653589793238462643383280 - pi_
print rjust(string(int(n)), 17); " "; ljust(string(pi_), 13); " "; ljust(string(error_), 13)
next
end

function getPi(n)
incircle = 0.0
for throws = 0 to n
incircle = incircle + (rand()^2 + rand()^2 < 1)
next
return 4.0 * incircle / throws
end function</syntaxhighlight>
{{out}}
<pre> Number of throws Ratio (Pi) Error
100 2.970297 0.17129562389
1000 3.14085914086 0.00073351273
10000 3.13208679132 0.00950586227
100000 3.14428855711 -0.00269590352
1000000 3.14041685958 0.00117579401
10000000 3.14094968591 0.000643
100000000 3.14153 0.00006264501</pre>


==={{header|BBC BASIC}}===
==={{header|BBC BASIC}}===
Line 538: Line 566:
[[File:Monte Carlo, 200 points, Locomotive BASIC.png]]
[[File:Monte Carlo, 200 points, Locomotive BASIC.png]]
[[File:Monte Carlo, 5000 points, Locomotive BASIC.png]]
[[File:Monte Carlo, 5000 points, Locomotive BASIC.png]]

==={{header|Run BASIC}}===
{{trans|Liberty BASIC}}
<syntaxhighlight lang="freebasic">for pow = 2 to 6
n = 10 ^ pow
print n; chr$(9); getPi(n)
next
end

function getPi(n)
incircle = 0
for throws = 0 to n
incircle = incircle + (rnd(1)^2 + rnd(1)^2 < 1)
next
getPi = 4 * incircle / throws
end function</syntaxhighlight>
{{out}}
<pre>100 3.12
1000 3.108
10000 3.1652
100000 3.14248
1000000 3.1435</pre>

==={{header|True BASIC}}===
{{trans|BASIC}}
<syntaxhighlight lang="qbasic">FUNCTION getpi(throws)
LET incircle = 0
FOR i = 1 to throws
!a square with a side of length 2 centered at 0 has
!x and y range of -1 to 1
LET randx = (rnd*2)-1 !range -1 to 1
LET randy = (rnd*2)-1 !range -1 to 1
!distance from (0,0) = sqrt((x-0)^2+(y-0)^2)
LET dist = sqr(randx^2+randy^2)
IF dist < 1 then !circle with diameter of 2 has radius of 1
LET incircle = incircle+1
END IF
NEXT i
LET getpi = 4*incircle/throws
END FUNCTION

CLEAR
PRINT getpi(10000)
PRINT getpi(100000)
PRINT getpi(1000000)
PRINT getpi(10000000)
END</syntaxhighlight>
{{out}}
<pre>3.1304
3.14324
3.141716
3.1416452</pre>


==={{header|PureBasic}}===
==={{header|PureBasic}}===