简体   繁体   中英

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 .

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

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 .

关于什么:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM