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
.
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.
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.
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 x
≤ y
. But then y-1
is an integer smaller than the smallest integer such that x
≤ y
, 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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With