Comment vérifier si un nombre est égale à 'NAN' ou 'INF' en python ?

Published: 21 septembre 2014

Tags: Python;

DMCA.com Protection Status

Exemples de comment vérifier si un nombre est égale à 'NAN' ou 'INF' en python:

Vérifier si un nombre est égale à 'NAN'

Pour tester si un nombre est égale à 'NAN', une solution est d'utiliser le module python math avec la fonction isnan()

import numpy as np
import math

x = 2.0

math.isnan(x)

donne

False

Tandis que

x = np.nan

math.isnan(x)

donne

True

Vérifier si un nombre est égale à 'INF'

Pour tester si un nombre est égale à 'INF', une solution est d'utiliser le module python math avec la fonction isinf()

import numpy as np
import math

x = 2.0

math.isinf(x)

donne

False

Tandis que

x = np.inf

math.isinf(x)

donne

True

Vérifier si un nombre est fini avec isfinite

On peut aussi utiliser la fonction. isfinite() pour tester si un nombre est fini:

>>> import numpy as np
>>> x = np.nan
>>> y = np.inf
>>> x
nan
>>> y
inf
>>> np.isfinite(x)
False
>>> np.isfinite(y)
False

Vérifier si une variable en python est un nombre avec isinstance

Pour vérifier si une variable en python est un nombre (int or float par exemple) une solution est d'utiliser isinstance:

x = 1.2

isinstance(x, (int, float))

donne dans ce cas

True

Tandis que

x = 'abcd'

isinstance(x, (int, float))

retourne

 false

Références