Soluions exercices 30 septembre

In [1]:
import numpy as np # import la librairie numpy (calcul scientifique)
import matplotlib.pyplot as plt # librairie pour afficher les graphs.
%matplotlib inline  

1) Produit scalaire

In [2]:
def ps_mat(x,y):
    
    return np.dot(x,y) # ou np.dot(x,y.T)
    # ou np.sum(x*y)
In [3]:
def ps_iter(x,y):
    
    s = 0
    for i in np.arange(len(x)):
        s += x[i] * y[i]
        
    return s
In [4]:
x = np.arange(10)
y = np.arange(10)
In [5]:
ps_mat(x,y)
Out[5]:
285
In [6]:
ps_iter(x,y)
Out[6]:
285
In [7]:
%timeit ps_mat(np.arange(123456),np.arange(123456))
1000 loops, best of 3: 773 ┬Ás per loop
In [8]:
%timeit ps_iter(np.arange(123456),np.arange(123456))
10 loops, best of 3: 48.3 ms per loop

2) Monte Carlo

In [9]:
def MonteCarlo(N=1000, scatter = True):
    
    x = np.random.rand(N)
    y = np.random.rand(N)
    
    z = x**2 + y**2
    n1 = (z<1).tolist().count(True)
    
    if scatter:
        plt.figure()
        plt.scatter(x[z<1], y[z<1], c='red')
        plt.scatter(x[z>1], y[z>1], c='blue')
    
    return n1/N
In [10]:
MonteCarlo(1000)
Out[10]:
0.787
In [11]:
list_N = np.linspace(50,100000,1000)
p = []
for N in list_N: 
    p.append(MonteCarlo(N, scatter = False)*4)
    
plt.plot(list_N,p)
Out[11]:
[<matplotlib.lines.Line2D at 0x7f31d341c128>]