Cours, pas TP - Outils de base

  1. Discord, voir : http://ljouhet.net
  2. JupyterHub : login, cellules, erreurs classiques
  3. Numpy
  4. Graphiques : matplotlib
  5. Types de base : listes, numpy, ligne par ligne

-> Euler

Erreurs classique

In [6]:
range n
  File "<ipython-input-6-8bd1a4d74178>", line 1
    range n
          ^
SyntaxError: invalid syntax
In [34]:
range(n)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-34-f908e15b3583> in <module>
----> 1 range(n)

NameError: name 'n' is not defined
In [ ]:
def f(x):
    return x**2
In [35]:
f(2)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-35-c510dc86724b> in <module>
----> 1 f(2)

NameError: name 'f' is not defined
In [38]:
for x in range(2)
    print(x)
  File "<ipython-input-38-d3322c9119ae>", line 1
    for x in range(2)
                     ^
SyntaxError: invalid syntax
In [39]:
x = range(10
print(x)
  File "<ipython-input-39-8f3aff15e3ae>", line 2
    print(x)
        ^
SyntaxError: invalid syntax

Numpy : array et calculs

In [7]:
import numpy as np
In [12]:
a = np.array([[1, 2, 3], [4, 5, 6]])
a
Out[12]:
array([[1, 2, 3],
       [4, 5, 6]])
In [13]:
a*1.5
Out[13]:
array([[1.5, 3. , 4.5],
       [6. , 7.5, 9. ]])
In [16]:
col = np.array([[1], [2], [3]])
lig = np.array([[1, 2, 3]])
dimension1 = np.array([1, 2, 3])
col, lig, dimension1
Out[16]:
(array([[1],
        [2],
        [3]]), array([[1, 2, 3]]), array([1, 2, 3]))
In [17]:
col.shape, lig.shape, dimension1.shape
Out[17]:
((3, 1), (1, 3), (3,))
In [19]:
y1, y2 = np.array([1, 2]), np.array([1, 1])
y1+3*y2, y1+0.5*y2
Out[19]:
(array([4, 5]), array([1.5, 2.5]))

Numpy : créer des séquences de valeurs

In [21]:
range(1, 10, 2), list(range(1, 10, 2))
Out[21]:
(range(1, 10, 2), [1, 3, 5, 7, 9])
In [22]:
range(1, 10, 0.5)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-22-9b6226ca7e45> in <module>
----> 1 range(1, 10, 0.5)

TypeError: 'float' object cannot be interpreted as an integer
In [24]:
# import numpy as
np.arange(1, 10, 0.5)          # a, b exclu, pas
Out[24]:
array([1. , 1.5, 2. , 2.5, 3. , 3.5, 4. , 4.5, 5. , 5.5, 6. , 6.5, 7. ,
       7.5, 8. , 8.5, 9. , 9.5])
In [25]:
np.linspace(1, 10, 7)          # a, b inclus, nb_pts
Out[25]:
array([ 1. ,  2.5,  4. ,  5.5,  7. ,  8.5, 10. ])
In [30]:
x = np.linspace(1, 10, 7)
y = np.sin(x)
y
Out[30]:
array([ 0.84147098,  0.59847214, -0.7568025 , -0.70554033,  0.6569866 ,
        0.79848711, -0.54402111])
In [9]:
%matplotlib inline
import matplotlib.pyplot as plt
In [11]:
x = np.linspace(0, 10, 20)
y = np.sin(x)
In [12]:
plt.plot(x, y)
Out[12]:
[<matplotlib.lines.Line2D at 0x7f52f72ab320>]
In [13]:
plt.plot(x, y, "+r", label="cool")
plt.legend()
Out[13]:
<matplotlib.legend.Legend at 0x7f52f7266710>
In [45]:
plt.plot([1, 2, 3], [7, 7, 7, 7])
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-45-0f8e274f0296> in <module>
----> 1 plt.plot([1, 2, 3], [7, 7, 7, 7])

/usr/local/lib/python3.6/dist-packages/matplotlib/pyplot.py in plot(scalex, scaley, data, *args, **kwargs)
   2787     return gca().plot(
   2788         *args, scalex=scalex, scaley=scaley, **({"data": data} if data
-> 2789         is not None else {}), **kwargs)
   2790 
   2791 

/usr/local/lib/python3.6/dist-packages/matplotlib/axes/_axes.py in plot(self, scalex, scaley, data, *args, **kwargs)
   1664         """
   1665         kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D._alias_map)
-> 1666         lines = [*self._get_lines(*args, data=data, **kwargs)]
   1667         for line in lines:
   1668             self.add_line(line)

/usr/local/lib/python3.6/dist-packages/matplotlib/axes/_base.py in __call__(self, *args, **kwargs)
    223                 this += args[0],
    224                 args = args[1:]
--> 225             yield from self._plot_args(this, kwargs)
    226 
    227     def get_next_color(self):

/usr/local/lib/python3.6/dist-packages/matplotlib/axes/_base.py in _plot_args(self, tup, kwargs)
    389             x, y = index_of(tup[-1])
    390 
--> 391         x, y = self._xy_from_xy(x, y)
    392 
    393         if self.command == 'plot':

/usr/local/lib/python3.6/dist-packages/matplotlib/axes/_base.py in _xy_from_xy(self, x, y)
    268         if x.shape[0] != y.shape[0]:
    269             raise ValueError("x and y must have same first dimension, but "
--> 270                              "have shapes {} and {}".format(x.shape, y.shape))
    271         if x.ndim > 2 or y.ndim > 2:
    272             raise ValueError("x and y can be no greater than 2-D, but have "

ValueError: x and y must have same first dimension, but have shapes (3,) and (4,)
In [56]:
%xmode Plain
plt.plot([1, 2, 3], [7, 7, 7, 7])
Exception reporting mode: Plain
Traceback (most recent call last):

  File "<ipython-input-56-c72667f925ae>", line 2, in <module>
    plt.plot([1, 2, 3], [7, 7, 7, 7])

  File "/usr/local/lib/python3.6/dist-packages/matplotlib/pyplot.py", line 2789, in plot
    is not None else {}), **kwargs)

  File "/usr/local/lib/python3.6/dist-packages/matplotlib/axes/_axes.py", line 1666, in plot
    lines = [*self._get_lines(*args, data=data, **kwargs)]

  File "/usr/local/lib/python3.6/dist-packages/matplotlib/axes/_base.py", line 225, in __call__
    yield from self._plot_args(this, kwargs)

  File "/usr/local/lib/python3.6/dist-packages/matplotlib/axes/_base.py", line 391, in _plot_args
    x, y = self._xy_from_xy(x, y)

  File "/usr/local/lib/python3.6/dist-packages/matplotlib/axes/_base.py", line 270, in _xy_from_xy
    "have shapes {} and {}".format(x.shape, y.shape))

ValueError: x and y must have same first dimension, but have shapes (3,) and (4,)

list et tuple vs array

In [47]:
a_list, b_list = [1, 2], [3, 4]
a_tuple, b_tuple = (1, 2), (3, 4)
a_array, b_array = np.array([1, 2]), np.array((3, 4))
In [49]:
a_list+b_list, a_tuple+b_tuple, a_array+b_array
Out[49]:
([1, 2, 3, 4], (1, 2, 3, 4), array([4, 6]))
In [50]:
2*a_list, 2*a_tuple, 2*a_array
Out[50]:
([1, 2, 1, 2], (1, 2, 1, 2), array([2, 4]))
In [51]:
2. * a_list
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-51-57cd74ba9d87> in <module>
----> 1 2.*a_list

TypeError: can't multiply sequence by non-int of type 'float'
In [52]:
2. * a_tuple
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-52-1696608ebc8f> in <module>
----> 1 2. * a_tuple

TypeError: can't multiply sequence by non-int of type 'float'
In [53]:
2. * a_array
Out[53]:
array([2., 4.])
In [55]:
y_0 = np.array([1, 2])
res_F = np.array([1, 1])
y = y_0 + 0.5 * res_F
y
Out[55]:
array([1.5, 2.5])

Astuce

Vous avez vu à la fin de la partie sur matplotlib à quoi sert %xmode Plain ?

Merci d'avoir lu jusque là !

In [ ]: