2

is it possible to create a custom NaN value in Python?

I know a bit about floating point representation and that NaN is a FP value with some special exponent. Therefore, each FP value with that special exponent is a NaN.

To be precise, what I want to do is:

x = make_my_special_NaN(int_seed)
assert math.isnan(x)
assert test_my_special_NaN(x, int_seed)
assert not test_my_special_NaN(float("nan"), int_seed)

The function which I called make_my_special_NaN should take an integer seed which can be used to identify the special NaN value I have (if this is possible).

Having this, it should be possible to test if a given NaN value is the special NaN given that integer seed.

Thanks in advance

Sven Hager
  • 3,144
  • 4
  • 24
  • 32
  • Need to know exactly what you need it to work for. numpy?? math(implied by your post) if you need math.isnan looks like it would take monkeypatching and `test_my_specail_NaN` would be fairly easy. – Phil Cooper Jul 02 '12 at 23:26

1 Answers1

1

The f and d format specifiers in struct will allow you to use any bit pattern you like.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • more specifically, `struct.unpack('!f', '\x7F\x80\x00\x01')` will unpack to a `float` NaN with a significand of 1. Replace the trailing 23 bits with anything but zero and you get a NaN. Same for `double` except the leading portion is `'\x7F\xF' and the significand is 52 bits. – D.Shawley Jul 03 '12 at 03:08