Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding to numpy.nextafter() float returns unexpected result

According to Wolfram Alpha, this is true for x > 2.

6.0/(x+16) > 2.0/(x+4)

To get the smallest possible x, I'm using numpy.nextafter().

>>> from numpy import nextafter
>>> x = nextafter(2,2+1)
>>> x
2.0000000000000004

However.

>>> 6.0/(x+16) > 2.0/(x+4)
False

Curiously.

>>> x+1
3.0000000000000004
>>> x+4
6.0

So how do I get the actual smallest possible x > 2 for this case?


1 Answers

import numpy as np

x = 2.0
while True:
    if 6.0/(x+16) > 2.0/(x+4): break
    x = np.nextafter(x, x+1)   
print(repr(x))

yields

2.0000000000000009

How floats are handled in CPython depends on the underlying C library. Most C libraries implement the IEEE 754 Standard for Floating-Point Arithmetic. However, "the IEEE standard does not guarantee that the same program will deliver identical results on all conforming systems." (See p. 249 of "What Every Computer Scientist Should Know about Floating-Point Arithmetic" (PDF) and also PEP 754).

To be able to predict the value x without iteration, one would have to study how floating point arithmetic is done (ibid (PDF)), write down x in its general binary format,

enter image description here

substitute this into the inequality

6.0/(x+16) > 2.0/(x+4)

and trace through the floating point arithmetic algorithms to solve for the digits dᵢ corresponding to the smallest float that satisifies the inequality.

like image 85
unutbu Avatar answered Apr 20 '26 20:04

unutbu