Java – Misconceptions about the ceil and floor methods

Misconceptions about the ceil and floor methods… here is a solution to the problem.

Misconceptions about the 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. …

Ceiling:

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 examples: System.out.print(Math.floor(2.8)); Returns 2.0. I will use this example to demonstrate this description: if floor(2.1) is the largest (closest to positive infinity), then the result will be 3.0 instead of 2.0, because I think 2.0 is closest to negative infinity. So if I change the description about the 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. …

This makes sense to me, I would understand that floor(2.1) returns 2.0

When I read “closest to positive infinity”

and “closest to negative infinity”, I thought on the number line:

The number line

Source: Quora

EDIT: What I’m asking: The description breaks my mind. My logic is (e.g. about floor): First, okay, when I listen to floor, I think it’s the smallest rather than the largest. Second, if I return the largest, i.e. greater than not less than the parameter. ceil

The same goes for it

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 point is that the phrase is less than or equal to the parameter.

So 2.0 is the maximum double value less than or equal to 2.1, which is also equal to an integer value.

The same goes for ceil: the minimum value greater than or equal to the input value is mentioned in the description….

Therefore, the original description is actually correct.

Related Problems and Solutions