Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find the largest integer less than x?

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

How would I get i the largest integer strictly smaller than x (as a 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 smaller than 2.0, which is 1.

like image 856
pheon Avatar asked Jan 03 '15 19:01

pheon


People also ask

How do you find the greatest integer less than or equal to X?

The greatest integer less than or equal to a number x is represented as ⌊x⌋. We will round off the given number to the nearest integer that is less than or equal to the number itself. Mathematically, the greatest integer function ⌊x⌋ can be defined as follows: ⌊x⌋ = n, where n ≤ x < n + 1 and 'n' is an integer.

What is the greatest integer less than or equal to?

And remember that it's the greatest integer less than or equal to, so the greatest integer less than or equal to zero is itself zero.


2 Answers

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

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

Else we have x in R \ Z and math.ceil(x) is the smallest integer y such that xy. But then y-1 is an integer smaller than the smallest integer such that xy, therefore x > y-1 and by construction y-1 is the largest such integer smaller than x.

It's simple enough that I wouldn't bother with those if-else. But to avoid computation errors with floats I would do the -1 outside the int conversion.

int(math.ceil(x))-1
like image 60
Lærne Avatar answered Oct 19 '22 05:10

Lærne


The following C code works in a certain sense---it gives you the next most negative integer that's representable as a floating-point number:

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

The following Python code is a 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 its second argument. It has a special case; if z < 0 and you ask for nextafter(0.0, z), it will return the smallest negative subnormal number.

From your specification, it is unclear what should be done 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 the most negative finite number to negative infinity.

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

like image 1
tmyklebu Avatar answered Oct 19 '22 05:10

tmyklebu