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 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
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments