Corrigé TD1

Préliminaires

In [1]:
print "Hello world!"
Hello world!
In [2]:
2**3-1
Out[2]:
7
In [3]:
"Hello world!"
Out[3]:
'Hello world!'

"Hello world!"

Définition de l'exponentielle: $$e^{x} = \sum_{n=0}^{\infty}\frac{x^n}{n!}$$

In [4]:
print 12/5
2
In [5]:
from __future__ import division
print 12/5
2.4
In [6]:
i=0
while i<10**9:
    i += 1
---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-6-195ecc641ac4> in <module>()
      1 i=0
      2 while i<10**9:
----> 3     i += 1

KeyboardInterrupt: 
In [7]:
print i
26680264

Prise en main de Python : petits exercices

Bibliothèques et modules

In [8]:
import math
help(math)
Help on built-in module math:

NAME
    math

FILE
    (built-in)

DESCRIPTION
    This module is always available.  It provides access to the
    mathematical functions defined by the C standard.

FUNCTIONS
    acos(...)
        acos(x)
        
        Return the arc cosine (measured in radians) of x.
    
    acosh(...)
        acosh(x)
        
        Return the hyperbolic arc cosine (measured in radians) of x.
    
    asin(...)
        asin(x)
        
        Return the arc sine (measured in radians) of x.
    
    asinh(...)
        asinh(x)
        
        Return the hyperbolic arc sine (measured in radians) of x.
    
    atan(...)
        atan(x)
        
        Return the arc tangent (measured in radians) of x.
    
    atan2(...)
        atan2(y, x)
        
        Return the arc tangent (measured in radians) of y/x.
        Unlike atan(y/x), the signs of both x and y are considered.
    
    atanh(...)
        atanh(x)
        
        Return the hyperbolic arc tangent (measured in radians) of x.
    
    ceil(...)
        ceil(x)
        
        Return the ceiling of x as a float.
        This is the smallest integral value >= x.
    
    copysign(...)
        copysign(x, y)
        
        Return x with the sign of y.
    
    cos(...)
        cos(x)
        
        Return the cosine of x (measured in radians).
    
    cosh(...)
        cosh(x)
        
        Return the hyperbolic cosine of x.
    
    degrees(...)
        degrees(x)
        
        Convert angle x from radians to degrees.
    
    erf(...)
        erf(x)
        
        Error function at x.
    
    erfc(...)
        erfc(x)
        
        Complementary error function at x.
    
    exp(...)
        exp(x)
        
        Return e raised to the power of x.
    
    expm1(...)
        expm1(x)
        
        Return exp(x)-1.
        This function avoids the loss of precision involved in the direct evaluation of exp(x)-1 for small x.
    
    fabs(...)
        fabs(x)
        
        Return the absolute value of the float x.
    
    factorial(...)
        factorial(x) -> Integral
        
        Find x!. Raise a ValueError if x is negative or non-integral.
    
    floor(...)
        floor(x)
        
        Return the floor of x as a float.
        This is the largest integral value <= x.
    
    fmod(...)
        fmod(x, y)
        
        Return fmod(x, y), according to platform C.  x % y may differ.
    
    frexp(...)
        frexp(x)
        
        Return the mantissa and exponent of x, as pair (m, e).
        m is a float and e is an int, such that x = m * 2.**e.
        If x is 0, m and e are both 0.  Else 0.5 <= abs(m) < 1.0.
    
    fsum(...)
        fsum(iterable)
        
        Return an accurate floating point sum of values in the iterable.
        Assumes IEEE-754 floating point arithmetic.
    
    gamma(...)
        gamma(x)
        
        Gamma function at x.
    
    hypot(...)
        hypot(x, y)
        
        Return the Euclidean distance, sqrt(x*x + y*y).
    
    isinf(...)
        isinf(x) -> bool
        
        Check if float x is infinite (positive or negative).
    
    isnan(...)
        isnan(x) -> bool
        
        Check if float x is not a number (NaN).
    
    ldexp(...)
        ldexp(x, i)
        
        Return x * (2**i).
    
    lgamma(...)
        lgamma(x)
        
        Natural logarithm of absolute value of Gamma function at x.
    
    log(...)
        log(x[, base])
        
        Return the logarithm of x to the given base.
        If the base not specified, returns the natural logarithm (base e) of x.
    
    log10(...)
        log10(x)
        
        Return the base 10 logarithm of x.
    
    log1p(...)
        log1p(x)
        
        Return the natural logarithm of 1+x (base e).
        The result is computed in a way which is accurate for x near zero.
    
    modf(...)
        modf(x)
        
        Return the fractional and integer parts of x.  Both results carry the sign
        of x and are floats.
    
    pow(...)
        pow(x, y)
        
        Return x**y (x to the power of y).
    
    radians(...)
        radians(x)
        
        Convert angle x from degrees to radians.
    
    sin(...)
        sin(x)
        
        Return the sine of x (measured in radians).
    
    sinh(...)
        sinh(x)
        
        Return the hyperbolic sine of x.
    
    sqrt(...)
        sqrt(x)
        
        Return the square root of x.
    
    tan(...)
        tan(x)
        
        Return the tangent of x (measured in radians).
    
    tanh(...)
        tanh(x)
        
        Return the hyperbolic tangent of x.
    
    trunc(...)
        trunc(x:Real) -> Integral
        
        Truncates x to the nearest Integral toward 0. Uses the __trunc__ magic method.

DATA
    e = 2.718281828459045
    pi = 3.141592653589793


In [9]:
from cmath import pi, exp
print exp(1j*pi)
(-1+1.22464679915e-16j)

Boucles et définition de fonctions

In [10]:
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)
24 24
40320 40320
In [11]:
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)
0.0497873792293 0.0497870683679
0.01 0.0119045038564
1e-05 3.40191461348e-06
1e-10 8.31445437131e-11

Graphe 2D

In [12]:
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()

Un générateur de nombres aléatoires

In [13]:
# la division entière
print 12345%123
print 5.42%1.2
45
0.62
In [14]:
# 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)
10 10 10 10 10 10 10 10 10 10
242 178 114 50 242 178 114 50 242 178
69 205 21 29 229 109 181 189 133 13
109621 27376 93139 95230 329 11100 85991 131314 58869 112480
31093 26296 62099 124390 31673 30516 46439 10450 51125 14408
102344 91499 87934 44609 73636 100535 56314 69549 120640 99435
168070 677268843 1194115201 1259501992 703671065 407145426 1010275440 1693606898 1702877348 745024267
840350 1238860568 1675608711 2002542666 1370871678 2035727130 756409906 2025583549 2071935799 1577637688
2100875 949667773 967796307 711389371 1279695548 794350531 1891024765 1842733402 1958614027 1796610573
Out[14]:
(None, None, None)

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$.

In [15]:
# 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) ]
[10213, 171649891L, 849180116L, 2141375297L, 416176606L, 325978763L, 494286244L, 1002156312L, 526892363L, 1404868360L]
In [16]:
# distribution uniforme

def Uniform(xmin,xmax):
    return (xmax-xmin)*aleatoire()/float(m-1)+xmin

print [ Uniform(-1,1) for i in range(10) ]
[-0.9629075126377005, 0.41343480852752434, 0.5988158607844412, 0.29815969178281687, -0.8300703659933716, -0.9926425805246853, 0.6561490648017723, -0.10268083783116266, 0.2431515494763401, 0.6480823202506474]

Manipulation de listes

In [17]:
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]
[0.8191030503999552, -0.8645940167669575, -0.9961666857170564, -0.6012414132807431, -0.29199385526900357, 8.035295952435462e-05, 0.18095718003630967, -0.22007916390127913, 0.04472582676816317, -0.9679913638834414]
In [18]:
moy = sum(reels)/len(reels)
print "Moyenne : {:.10f}".format(moy)
Moyenne : 0.0159014747
In [19]:
from math import sqrt
stdev = sqrt(sum([ (x-moy)**2 for x in reels ])/len(reels))
print "Ecart-type : {:.10f}".format(stdev)
Ecart-type : 0.5898462271
In [20]:
import numpy as np
print np.mean(reels), np.std(reels)
0.0159014747344 0.589846227119