How to find the largest integer less than x?

If x is 2.3 , then math.floor(x) returns 2.0 , the largest integer less than or equal to x (like float.)

How would i get the largest integer strictly less than x (as an integer)?

The best I came up with is:

 i = int(math.ceil(x)-1) 

Is there a better way?

Note that if x is 2.0 , then math.floor(x) returns 2.0 , but I need the largest integer less than 2.0 , which is 1 .

+7
python math floating-point
source share
3 answers

math.ceil(x)-1 is correct, and here is the proof.

if x is in Z (a set of integers), then math.ceil(x) = x . Therefore, math.ceil(x)-1 = x-1 , the largest integer is less than x .

Otherwise, we have x in R \ Z , and math.ceil(x) is the smallest integer y such that x ≀ y . But then y-1 is an integer less than the smallest integer such that x ≀ y , so x > y-1 and by construction y-1 is the largest such integer less than x .

It is simple enough that I would not bother with these if - else . But in order to avoid calculation errors using float, I would do -1 outside the int conversion.

 int(math.ceil(x))-1 
+3
source share

The following C code works in a certain sense --- it gives you the following most negative integer, which is represented as a floating point number:

 double flooor(double x) { return floor(nextafter(x, -1.0/0.0)); } 

The following Python code is direct transliteration, but it relies on NumPy:

 def flooor(x): return math.floor(numpy.nextafter(x, -numpy.inf)) 

The nextafter function moves from its first argument one double closer to the second argument. He has a special case; if z < 0 , and you ask for nextafter(0.0, z) , it will return the smallest negative negative number.

It is not clear from your specification what to do with positive infinity and the most negative finite number. This code sends positive infinity to the most positive finite number, negative infinity to itself and to the most negative finite number to negative infinity.

Martijn Pieters gave the int(math.ceil(x)) - 1 spell in his answer since it was deleted. This correctly finds the largest int less than float x . This round x up, converts it to an integer and subtracts 1, giving the largest Python int , which is numerically smaller than x .

+1
source share

What about:

 i = int(math.floor(x) - 1) 
-2
source share

All Articles