Visualiser la marche
Visualisons cette marche aléatoire ! Vous souvenez-vous comment utiliser matplotlib pour créer un graphique linéaire ?
import matplotlib.pyplot as plt
plt.plot(x, y)
plt.show()
La première liste que vous passez est associée à l'axe x et la seconde liste à l'axe y.
Si vous ne passez qu'un seul argument, Python saura quoi faire : il utilisera l'indice de la liste pour l'axe x et les valeurs de la liste pour l'axe y.
Cette activité fait partie du cours
Python intermédiaire
Instructions de l’exercice
Ajoutez quelques lignes de code après la boucle for :
- Importez
matplotlib.pyplotsous le nomplt. - Utilisez
plt.plot()pour tracerrandom_walk. - Terminez avec
plt.show()pour afficher le graphique.
Exercice interactif pratique
Essayez cet exercice en complétant ce code d’exemple.
# NumPy is imported, seed is set
# Initialization
random_walk = [0]
for x in range(100) :
step = random_walk[-1]
dice = np.random.randint(1,7)
if dice <= 2:
step = max(0, step - 1)
elif dice <= 5:
step = step + 1
else:
step = step + np.random.randint(1,7)
random_walk.append(step)
# Import matplotlib.pyplot as plt
# Plot random_walk
# Show the plot