nan_to_num

array_api_extra.nan_to_num(x, /, *, fill_value=0.0, xp=None)

Replace NaN with zero and infinity with large finite numbers (default behaviour).

If x is inexact, NaN is replaced by zero or by the user defined value in the fill_value keyword, infinity is replaced by the largest finite floating point value representable by x.dtype, and -infinity is replaced by the most negative finite floating point value representable by x.dtype.

For complex dtypes, the above is applied to each of the real and imaginary components of x separately.

Parameters:
  • x (object | complex) – Input data.

  • fill_value (float) – Value to be used to fill NaN values. If no value is passed then NaN values will be replaced with 0.0.

  • xp (ModuleType | None) – The standard-compatible namespace for x. Default: infer.

Returns:

x, with the non-finite values replaced.

Return type:

object

See also

array_api.isnan

Shows which elements are Not a Number (NaN).

Examples

>>> import array_api_extra as xpx
>>> import array_api_strict as xp
>>> xpx.nan_to_num(xp.inf, xp=xp)
Array(1.79769313e+308, dtype=array_api_strict.float64)
>>> xpx.nan_to_num(-xp.inf, xp=xp)
Array(-1.79769313e+308, dtype=array_api_strict.float64)
>>> xpx.nan_to_num(xp.nan, xp=xp)
Array(0., dtype=array_api_strict.float64)
>>> x = xp.asarray([xp.inf, -xp.inf, xp.nan, -128, 128])
>>> xpx.nan_to_num(x)
Array([ 1.79769313e+308, -1.79769313e+308,  0.00000000e+000,
       -1.28000000e+002,  1.28000000e+002],
      dtype=array_api_strict.float64)
>>> y = xp.asarray([complex(xp.inf, xp.nan), xp.nan, complex(xp.nan, xp.inf)])
>>> xpx.nan_to_num(y)
Array([1.79769313e+308+0.00000000e+000j,
       0.00000000e+000+0.00000000e+000j,
       0.00000000e+000+1.79769313e+308j],
      dtype=array_api_strict.complex128)