Montecarlo - WordPress.com

Transcripción

Montecarlo - WordPress.com
--------------------------TEMA 3---------------------------------------------------MÉTODO DE MONTECARLO ----------------------PARA ESTE TEMA, SE IMPLEMENTARON SOLUCIONES PARA PROBLEMAS DE
CÁLCULOS DE ÁREA Y VOLÚMENES MEDIANTE MONTECARLO. PARA ESTO, ES
NECESARIA LA GENERACIÓN DE NÚMEROS ALEATORIOS QUE SE HIZO A
TRAVÉS DE UN GENERADOR OBTENIDO DE NUMERICAL RECIPES FOR
ENGINEERS. EL CÓDIGO PARA LA GENERACIÓN DE NÚMEROS ALEATORIOS SE
AÑADIÓ COMO HEADER EN TODOS LOS PROGRAMAS Y ES EL SIGUIENTE:
//
//
//
//
//
//
//
Random_3.h
Random Recipe
Created by Alexis Mobayed on 4/14/16.
Copyright © 2016 Alexis Mobayed. All rights reserved.
#ifndef Random_h
#define Random_h
#endif
#include <math.h>
#define MBIG 1000000000
#define MSEED 161803398
#define MZ 0
#define FAC (1.0/MBIG)
float ran3(long *idum)
{
static int inext,inextp; static long ma[56]; static int
iff=0;
long mj,mk;
int i,ii,k;
if (*idum < 0 || iff == 0) { iff=1;
mj=labs(MSEED-labs(*idum)); mj %= MBIG;
ma[55]=mj;
mk=1;
for (i=1;i<=54;i++) { ii=(21*i) % 55; ma[ii]=mk; mk=mjmk;
if (mk < MZ) mk += MBIG;
mj=ma[ii];
}
for (k=1;k<=4;k++)
for (i=1;i<=55;i++) {
ma[i] -= ma[1+(i+30) % 55];
if (ma[i] < MZ) ma[i] += MBIG; }
inext=0;
inextp=31;
*idum=1;
}
if (++inext == 56) inext=1; if (++inextp == 56) inextp=1;
mj=ma[inext]-ma[inextp];
if (mj < MZ) mj += MBIG; ma[inext]=mj;
return mj*FAC;
}
--------------CÁLCULO DE PI A TRAVÉS DE MONTECARLO-------------//
//
//
//
//
//
//
main.cpp
Montecarlo
Created by Alexis Mobayed on 19/04/16.
Copyright © 2016 Adolfo Galindo. All rights reserved.
#include <iostream>
#include "Random2.h"
using namespace std;
int main()
{
float g, h, m, res, p=0, k=0;
long ss=3345, *seed=&ss;
for(int i=0; i<10000000; i++)
{
g=ran2(seed);
h=ran2(seed);
m=(g*g)+(h*h);
if(m<1)
p++;
else
k++;
}
cout<<p;
cout<<endl;
cout<<k;
cout<<endl;
res=(p/(p+k))*4.0;
cout<<res;
cout<<endl;
}
--------------CÁLCULO DE PI A TRAVÉS DE MONTECARLO--------------
------CÁLCULO DEL VOLUMEN DE UN TORO MEDIANTE MONTECARLO--------
//
//
//
//
//
//
//
main.cpp
Montecarlo
Created by Alexis Mobayed on 4/19/16.
Copyright © 2016 Alexis Mobayed. All rights reserved.
#include <iostream>
#include "Random.h"
using namespace std;
int main(int argc, const char * argv[])
{
float g,res,p=0,k=0,r,R,vol;
long ss=3345,*seed=&ss;
cout<<"Por favor dame el radio del círculo de la sección
transversal: ";
cin>>r;
cout<<"Por favor dame el radio del toro: ";
cin>>R;
for(int i=0;i<20000000;i++)
{
g=ran3(seed)*(r*2);
if(g<r)
p++;
else
k++;
}
res=((p/(p+k))*pow(2*r,2)*3.1416)/2;
cout<<"El área de la sección transversal es "<<res<<endl;
vol=res*2*R*3.1416;
cout<<"El volumen del toro es: "<<vol<<endl;
}
------CÁLCULO DEL VOLUMEN DE UN TORO MEDIANTE MONTECARLO--------

Documentos relacionados