Search code examples
javamaththeoryfloorceil

Java - Misunderstand ceil and floor methods


floor:

Returns the largest (closest to positive infinity) double value that is less than or equal to the argument and is equal to a mathematical integer. ...

ceil:

Returns the smallest (closest to negative infinity) double value that is greater than or equal to the argument and is equal to a mathematical integer. ...

Source: Docs Oracle

About floor: If I type System.out.print(Math.floor(2.1)); returns 2.0 . Other example: System.out.print(Math.floor(2.8)); returns 2.0 . I am going to argue this description with the example: if floor(2.1) was the largest (closest to positive infinity) as a result would be 3.0 not 2.0, because 2.0 is closest to negative infinity I think. So if I change the description about floor:

Returns the smallest (closest to negative infinity) double value that is less than or equal to the argument and is equal to a mathematical integer. ...

It makes sense for me, I would understand that floor(2.1) returns 2.0

When I read "closest to positive infinity" and "closest to negative infinity" I think in the number line:

The number line

Source: Quora

EDIT: What I am asking is: the description broke my mind. My logic says (about floor for example): First, Ok when I listen floor I think in the smallest not in the largest. Second, if I returns the largest, that is greater not less than to the argument. The same happens with ceil


Solution

  • Returns the largest (closest to positive infinity) double value that is less than or equal to the argument and is equal to a mathematical integer

    The key is in the phrase that is less than or equal to the argument.

    So 2.0 is the largest double value that is less than or equal to 2.1 that is also equal to an integer value.

    Ditto for ceil: the description mentions the smallest value that is larger or equal to the input value...

    So, the original descriptions are in fact correct.