Monte Carlo methods: Difference between revisions
Content added Content deleted
(Added solution for Action!) |
|||
Line 134: | Line 134: | ||
10**6 1000000 samples give Pi=3.141180 |
10**6 1000000 samples give Pi=3.141180 |
||
10**7 10000000 samples give Pi=3.141677 |
10**7 10000000 samples give Pi=3.141677 |
||
</pre> |
|||
=={{header|Action!}}== |
|||
{{libheader|Action! Tool Kit}} |
|||
{{libheader|Action! Real Math}} |
|||
<lang Action!>INCLUDE "H6:REALMATH.ACT" |
|||
DEFINE PTR="CARD" |
|||
DEFINE REAL_SIZE="6" |
|||
BYTE ARRAY realArray(1536) |
|||
PTR FUNC RealArrayPointer(BYTE i) |
|||
PTR p |
|||
p=realArray+i*REAL_SIZE |
|||
RETURN (p) |
|||
PROC InitRealArray() |
|||
REAL r2,r255,ri,div |
|||
REAL POINTER pow |
|||
INT i |
|||
IntToReal(2,r2) |
|||
IntToReal(255,r255) |
|||
FOR i=0 TO 255 |
|||
DO |
|||
IntToReal(i,ri) |
|||
RealDiv(ri,r255,div) |
|||
pow=RealArrayPointer(i) |
|||
Power(div,r2,pow) |
|||
OD |
|||
RETURN |
|||
PROC CalcPi(INT n REAL POINTER pi) |
|||
BYTE x,y |
|||
INT i,counter |
|||
REAL tmp1,tmp2,tmp3,r1,r4 |
|||
REAL POINTER pow |
|||
counter=0 |
|||
IntToReal(1,r1) |
|||
IntToReal(4,r4) |
|||
FOR i=1 TO n |
|||
DO |
|||
x=Rand(0) |
|||
pow=RealArrayPointer(x) |
|||
RealAssign(pow,tmp1) |
|||
y=Rand(0) |
|||
pow=RealArrayPointer(y) |
|||
RealAssign(pow,tmp2) |
|||
RealAdd(tmp1,tmp2,tmp3) |
|||
IF RealGreaterOrEqual(tmp3,r1)=0 THEN |
|||
counter==+1 |
|||
FI |
|||
OD |
|||
IntToReal(counter,tmp1) |
|||
RealMult(r4,tmp1,tmp2) |
|||
IntToReal(n,tmp3) |
|||
RealDiv(tmp2,tmp3,pi) |
|||
RETURN |
|||
PROC Test(INT n) |
|||
REAL pi |
|||
PrintF("%I samples -> ",n) |
|||
CalcPi(n,pi) |
|||
PrintRE(pi) |
|||
RETURN |
|||
PROC Main() |
|||
Put(125) PutE() ;clear the screen |
|||
PrintE("Initialization of data...") |
|||
InitRealArray() |
|||
Test(10) |
|||
Test(100) |
|||
Test(1000) |
|||
Test(10000) |
|||
RETURN</lang> |
|||
{{out}} |
|||
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Monte_Carlo_methods.png Screenshot from Atari 8-bit computer] |
|||
<pre> |
|||
Initialization of data... |
|||
10 samples -> 3.2 |
|||
100 samples -> 3.28 |
|||
1000 samples -> 3.212 |
|||
10000 samples -> 3.1156 |
|||
</pre> |
</pre> |
||