# première version
def aleatoire(un):
return (a*un+c)%m
def affiche(graine,n=10):
rand = graine
for i in range(n):
rand = aleatoire(rand)
print(rand,end=" ")
print()
# wikipedia non-optimal
a, c, m = 25, 16, 256
affiche(10), affiche(50), affiche(125)
print()
# quickran choice
a, c, m = 8121, 28411, 134456
affiche(10), affiche(50), affiche(125)
print()
# standard minimum
a, c, m = 16807, 0, 2**31-1
affiche(10), affiche(50), affiche(125)
# deuxième version avec le mot-clé global
graine = 10213
a, c, m = 16807, 0, 2**31-1
u = graine
def aleatoire():
global u # nécessaire pour utiliser le u défini au-dessus et non une variable 'u' locale
last, u = u, (a*u+c)%m
return last
print ([ aleatoire() for i in range(10) ])
# distribution uniforme
def Uniform(xmin,xmax):
return (xmax-xmin)*aleatoire()/float(m-1)+xmin
print ([ Uniform(-1,1) for i in range(10) ])
reels = [ Uniform(-1,1) for i in range(1000) ]
# ou
from random import uniform
reels = [ uniform(-1,1) for i in range(1000) ]
print(reels[:10])
moy = sum(reels)/len(reels)
print ("Moyenne : {:.10f}".format(moy))
from math import sqrt
stdev = sqrt(sum([ (x-moy)**2 for x in reels ])/len(reels))
print ("Ecart-type : {:.10f}".format(stdev))
import numpy as np
print(np.mean(reels), np.std(reels))
# Algorithme de Verlet
def Verlet(r0,v0,tf,F,N=100):
Fx, Fz = F
dt = tf/float(N)
x, z = [0.0]*N, [0.0]*N
x[0], z[0] = r0[0], r0[1]
x[1] = x[0] + v0[0]*dt + 0.5*Fx(x[0],z[0])*dt**2
z[1] = z[0] + v0[1]*dt + 0.5*Fz(x[0],z[0])*dt**2
for i in range(2,N):
x[i] = 2*x[i-1]-x[i-2] + Fx(x[i-1],z[i-1])*dt**2
z[i] = 2*z[i-1]-z[i-2] + Fz(x[i-1],z[i-1])*dt**2
return (x,z)
from pylab import *
%matplotlib inline
from math import cos, sin, tan, pi
g, v0, h = 9.81, 0.2, 1.0
def Fx(x,z): return 0.0
def Fz(x,z): return -g
N, tf = 100, 0.5
for theta in [pi/5,pi/4,pi/3]:
(x,z) = Verlet((0.0,h),(v0*sin(theta),v0*cos(theta)),tf,(Fx,Fz),N)
plot(x, z)
def Exact(x): return h + x/tan(theta) -0.5*g*(x/(v0*sin(theta)))**2
plot(x, [ Exact(pos) for pos in x ],'+')
show()
theta = pi/4
(x,z) = Verlet((0.0,h),(v0*sin(theta),v0*cos(theta)),tf,(Fx,Fz),N)
def Exact(x): return h + x/tan(theta) -0.5*g*(x/(v0*sin(theta)))**2
diff = [ abs(Exact(x[i])-z[i])**0.5 for i in range(len(x)) ]
plot(diff)
show()
# une fonction qui détermine la position au sol à partir de (x,z)
def Position(x,z):
for i in range(len(z)):
if z[i] < 0.0:
break
# return x[i] # version sans interpolation assez sommaire
return x[i] - z[i]*(x[i]-x[i-1])/(z[i]-z[i-1]) # avec interpolation linéaire
Npoints, thetamin, thetamax = 1000, pi/5, pi/3
dtheta = (thetamax-thetamin)/float(Npoints-1)
Thetas = [thetamin + i*dtheta for i in range(Npoints) ]
pos = []
for theta in Thetas:
(x,z) = Verlet((0.0,h),(v0*sin(theta),v0*cos(theta)),tf,(Fx,Fz),N)
pos.append(Position(x,z))
n, bin, patches = hist(pos, bins=100, range=(0.05,0.085), normed=1, facecolor='white')
xlabel('x')
ylabel('H(x)')
title('Histogramme des valeurs de $x$')
show()