63 lines
1.7 KiB
Org Mode
63 lines
1.7 KiB
Org Mode
:PROPERTIES:
|
|
:ID: f7c05933-90e6-4a9c-acd5-1f0baf62f07f
|
|
:mtime: 20220528103954
|
|
:ctime: 20220206220528
|
|
:END:
|
|
#+title: Arrondir les flottants en python
|
|
#+filetags: :Python:
|
|
|
|
* Arrondir à l'entier le plus proche
|
|
** Avec la fonction /built-in/ /round/
|
|
#+BEGIN_SRC python :results output
|
|
print(f"{round(7 / 2) = }")
|
|
print(f"{round(3 / 2) = }")
|
|
print(f"{round(5 / 2) = }")
|
|
#+END_SRC
|
|
|
|
#+RESULTS:
|
|
: round(7 / 2) = 4
|
|
: round(3 / 2) = 2
|
|
: round(5 / 2) = 2
|
|
|
|
~round(5 / 2)~ retourne 2 et non 3 car la fonction /built-in/ implémente l'[[https://fr.wikipedia.org/wiki/Arrondi_(math%C3%A9matiques)#Arrondi%20au%20pair%20le%20plus%20proche][arrondi au pair le plus proche]].
|
|
|
|
* Arrondir un nombre à l'entier inférieur
|
|
#+BEGIN_SRC python :results output
|
|
print(22 // 5)
|
|
#+END_SRC
|
|
#+RESULTS:
|
|
: 4
|
|
|
|
* Arrondir un noombre à l'entier supérieur
|
|
** Arithmétique simple
|
|
#+BEGIN_SRC python :results output
|
|
n = 22
|
|
div = 5
|
|
print(f'{int(n/div) + (n % div>0) = }')
|
|
#+END_SRC
|
|
#+RESULTS:
|
|
: int(n/div) + (n % div>0) = 5
|
|
|
|
** Opérateur à étage // (ne fonctionne qu'avec les entiers)
|
|
L'opérateur à étage // se comporte comme l'opérateur de division /, à la différence que le résultat est arrondi à
|
|
l'entier inférieur :
|
|
#+BEGIN_SRC python :results output
|
|
print(22 // -5 * -1)
|
|
#+END_SRC
|
|
#+RESULTS:
|
|
: 5
|
|
|
|
** Méthode /numpy.ceil/
|
|
#+BEGIN_SRC python :results output
|
|
from numpy import ceil
|
|
|
|
print(int(ceil(22 / 5)))
|
|
#+END_SRC
|
|
#+RESULTS:
|
|
: 5
|
|
|
|
* Références
|
|
* [[https://medium.com/@saint_sdmn/10-hardest-python-questions-98986c8cd309][10 Hardest Python Questions - Medium]]
|
|
* [[id:f7c05933-90e6-4a9c-acd5-1f0baf62f07f][Arrondir les flottants en python]]
|
|
* [[https://www.delftstack.com/fr/howto/python/python-round-up/][Arrondir un nombre en Python]]
|