29

I need to find a numpy.float64 value that is as close to zero as possible.

Numpy offers several constants that allow to do something similar:

  • np.finfo(np.float64).eps = 2.2204460492503131e-16
  • np.finfo(np.float64).tiny = 2.2250738585072014e-308

These are both reasonably small, but when I do this

>>> x = np.finfo(np.float64).tiny
>>> x / 2
6.9533558078350043e-310

the result is even smaller. When using an impromptu binary search I can get down to about 1e-323, before the value is rounded down to 0.0.

Is there a constant for this in numpy that I am missing? Alternatively, is there a right way to do this?

m00am
  • 5,910
  • 11
  • 53
  • 69
  • 4
    Use np.nextafter. Almost a duplicate: http://stackoverflow.com/questions/6063755/increment-a-python-floating-point-value-by-the-smallest-possible-amount – ev-br Jul 20 '16 at 09:57
  • Thanks, this is exactly what I needed. If you write this as an answer I will gladly accept it. I agree that the topic of the question you linked is similar, but I would have never thought about looking for those keyword with my problem. – m00am Jul 20 '16 at 11:24
  • May I ask why you need this? Just to make sure you're not trapped by an XY problem:) – Andras Deak -- Слава Україні Jul 20 '16 at 12:43
  • Primarily out of curiosity. A coworker asked me if I know how to do this and I couldn't come up with a better answer than "Let's ask this on SO". I don't know his precise application though. – m00am Jul 20 '16 at 13:18
  • 2
    FYI: The floating point values between 0 and `np.finfo(np.float64).tiny` are known as "denormal" or "subnormal" numbers: https://en.wikipedia.org/wiki/Denormal_number – Warren Weckesser Jul 20 '16 at 13:51
  • Not to be confused with "abnormal" numbers. – devinbost Feb 10 '18 at 01:51

2 Answers2

30

Use np.nextafter.

>>> import numpy as np
>>> np.nextafter(0, 1)
4.9406564584124654e-324
>>> np.nextafter(np.float32(0), np.float32(1))
1.4012985e-45
ev-br
  • 24,968
  • 9
  • 65
  • 78
  • this function gave me zero, why ? – Feras Oct 28 '17 at 10:12
  • @Feras, I'm a bit late to the party, but that's an indication that FTZ bit is set in your FPU. Can happen when e.g. loading a shared object which was compiled with "fast math" enabled. – Bjoern Dahlgren Oct 04 '21 at 12:14
1

2^-1075 is the smallest positive float. 2^-1075 = 5.10^-324

Simo
  • 155
  • 3
  • 12