Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nan with Python 2.5 on Windows

How do I create a Nan with Python 2.5 on Windows?

float('nan') fails with the error ValueError: invalid literal for float(): nan

Summary of the answers: Neither float('inf') nor float('nan') works with Python 2.5 and Windows. This is a bug that was fixed in Python 2.6.

If you are using numpy, then you can use numpy.inf and numpy.nan.

If you need a workaround without numpy, then you can use an expression that overflows such as 1e1000 to get an inf, and 1e1000 / 1e1000 or 1e1000 - 1e1000 to get a nan.

like image 411
Johan Råde Avatar asked May 19 '26 10:05

Johan Råde


2 Answers

Another way is dividing inf by itself:

>>> float('inf') / float('inf')
nan

Or in a more obscure way, which might not work across platforms (but works around that specific bug in Python 2.5 on Windows):

>>> 1e31337 / 1e31337
nan
>>> 1e31337 - 1e31337
nan
like image 138
Niklas B. Avatar answered May 21 '26 23:05

Niklas B.


There is already an accepted answer to this question, but I think the following should work if you don't want to rely on overflow and have numpy installed ... (not tested as I don't have python2.5 or windows)

>>> import numpy as np
>>> np.nan
nan
>>> np.inf
inf
like image 40
mgilson Avatar answered May 21 '26 23:05

mgilson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!