Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #285 Set variable to NaN

Given two floating point variables a and b, set a to a to a quiet NaN and b to a signalling NaN. Use standard features of the language only, without invoking undefined behavior.

a = Float::NAN
#include <limits>
a = std::numeric_limits<float>::quiet_NaN();
b = std::numeric_limits<float>::signaling_NaN();
    use, intrinsic :: ieee_arithmetic, only: IEEE_Value, IEEE_QUIET_NAN, IEEE_SIGNALING_NAN
 a = ieee_value (a, IEEE_QUIET_NAN)
 b = ieee_value (b, IEEE_SIGNALING_NAN)
local a = 0/0
math
a := NaN;
use feature 'say';
# built-in support (use POSIX not needed))
my $a = 'nan';

say $a;
# prints string value: nan

say 0 + $a;
# prints numeric value: NaN

use feature 'say';
use POSIX qw(:nan_payload nan isnan issignaling getpayload);
say isnan($a) ? 'true' : 'false';;
# prints true

say $a == $a ? 'true' : 'false';
# prints false because NaN does not equal NaN

say issignaling($a) ? 'true' : 'false';
# prints false because $a is non-signaling

my $b = nan(999);  # set to signaling NaN by adding a payload

say $b;
# prints NaN

say getpayload($b);
# prints 999
a = float('nan')
from decimal import Decimal
a, b = Decimal('NaN'), Decimal('sNaN')
let a: f64 = f64::NAN;

New implementation...
< >
tkoenig