print "Hello world!"
2**3-1
"Hello world!"
"Hello world!"
Définition de l'exponentielle: $$e^{x} = \sum_{n=0}^{\infty}\frac{x^n}{n!}$$
print 12/5
from __future__ import division
print 12/5
i=0
while i<10**9:
i += 1
print i
import math
help(math)
from cmath import pi, exp
print exp(1j*pi)
def Factorielle(n):
res = 1
for i in range(1,n+1):
res *= i
return res
from math import factorial
print Factorielle(4), factorial(4)
def Factorielle(n):
if n == 1 or n == 0: return 1
return n*Factorielle(n-1)
print Factorielle(8), factorial(8)
def Exp(x,precision=1e-5):
res, n = 1.0, 1
condition = abs(x) > precision # terme 1+x
while condition:
an = x**n/factorial(n)
res += an
condition = abs(x/(n+1.0)*an/res) > precision # a_{n+1} = x/(n+1)*a_n
n += 1
return res
from math import exp
print Exp(-3.0), exp(-3.0)
r = 3.0
for p in [1e-2,1e-5,1e-10]:
print p, abs(Exp(r,p)-exp(r))/exp(r)
from pylab import *
%matplotlib inline
npoints, xmin, xmax = 101, -3.0, 3.0
dx = (xmax-xmin) / (npoints-1)
f = lambda x: exp(x)
t = [ xmin + dx*i for i in range(npoints) ]
s = map(f,t)
plot(t, s)
xlabel('$x$')
ylabel('$e^x$')
title('La fonction exponentielle')
grid(True)
show()
# la division entière
print 12345%123
print 5.42%1.2
# 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,
print
# wikipedia non-optimal
a, c, m = 25, 16, 256
affiche(10), affiche(50), affiche(125)
# quickran choice
a, c, m = 8121, 28411, 134456
affiche(10), affiche(50), affiche(125)
# standard minimum
a, c, m = 16807, 0, 2**31-1
affiche(10), affiche(50), affiche(125)
On voit que la formule peut générer des nombres au moins aussi grands que $m$ avant d'appliquer la division entière. Celle-ci retourne le reste de la division par $m$, c'est-à-dire des entiers compris entre $0$ et $m-1$.
# 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)