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

1
  • 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. Commented Jul 2, 2012 at 23:26

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.