Demo entry 6655136

Monte Carlo

   

Submitted by anonymous on Oct 25, 2017 at 20:30
Language: Python 3. Code size: 2.0 kB.

import matplotlib .pyplot as plt
import math as m

## Générateur de Von Neumann

def Neumann (x0) :
    x0*=x0
    x0=int(x0/1000)
    x0-=100000000*int(x0/100000000)
    x0-=10000000*int(x0/10000000)
    x0-=1000000*int(x0/1000000)
    return (x0)
    
def Von_Neumann(xn) :
    if (xn<=0) or (xn>999999) :
        return (False)
    else :
        return(Neumann(xn))
        
def Random (X0,N) :
    RandList=[X0/1000000]
    for k in range (0,N-1) :
        RandList.append(float(Neumann(RandList[-1]*1000000)/1000000))
    return (RandList)

## Vérification de la Qualité du Générateur de Von Neumann

def verification (seed,N) : # Avec 654321 et 1000000
    RandList=Random(seed,N)
    x=[]
    y=[]
    for k in range (0,N-2) :
        x.append(RandList[k])
        y.append(RandList[k+1])
    plt.clf()
    plt.plot(x,y,ls='',marker='.',color='darkcyan')
    plt.show()
    
## Algorithme de Génération à congruence linéaire

def congru_lin (xn,a,c,m) :
    return ((a*xn+c)%m)

def Random2(x0,a,c,m,N) :
    RandList=[x0/(m-1)]
    for k in range (0,N-1) :
        RandList.append(congru_lin(RandList[-1],a,c,m)/(m-1))
    return (RandList)
    
## Vérification de la Qualité du Générateur à Congruence Linéaire

def verification2 (seed,a,c,m,N) : # Avec 77,1103515245,12345,231,1000000
    RandList=Random2(seed,a,c,m,N)
    x=[]
    y=[]
    for k in range (0,N-2) :
        x.append(RandList[k])
        y.append(RandList[k+1])
    plt.clf()
    plt.plot(x,y,ls='',marker='.',color='red')
    plt.show()
    
## Méthode de Monte Carlo

def f(x) :
    return (m.sin(x))

def MonteCarlo(x0,a,b,p0,N,f) :
    A=(b-a)*p0
    theta=0
    RandList=Random2(77,1103515245,12345,231,N+2)
    x=[]
    y=[]
    for k in range (1,N) :
        x.append(RandList[k]*(b-a)+a)
        y.append(RandList[k+1]*p0)
        
    for k in range (0,N-1) :
        if (y[k]<=f(x[k])) :
            theta+=1
    return (A*theta/N)

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).