Skip to content

Commit f905314

Browse files
committed
refactor: refactor Ceil and improved tests
1 parent f325279 commit f905314

File tree

2 files changed

+20
-17
lines changed

2 files changed

+20
-17
lines changed
Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,27 @@
11
package com.thealgorithms.maths;
22

3+
/**
4+
* Utility class to compute the ceiling of a given number.
5+
*/
36
public final class Ceil {
7+
48
private Ceil() {
59
}
610

711
/**
8-
* Returns the smallest (closest to negative infinity)
12+
* Returns the smallest double value that is greater than or equal to the input.
13+
* Equivalent to mathematical ⌈x⌉ (ceiling function).
914
*
10-
* @param number the number
11-
* @return the smallest (closest to negative infinity) of given
12-
* {@code number}
15+
* @param number the number to ceil
16+
* @return the smallest double greater than or equal to {@code number}
1317
*/
1418
public static double ceil(double number) {
15-
if (number - (int) number == 0) {
16-
return number;
17-
} else if (number - (int) number > 0) {
18-
return (int) (number + 1);
19+
long intPart = (long) number;
20+
21+
if (number > 0 && number != intPart) {
22+
return intPart + 1.0;
1923
} else {
20-
return (int) number;
24+
return (double) intPart;
2125
}
2226
}
2327
}

src/test/java/com/thealgorithms/maths/CeilTest.java

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,15 @@
22

33
import static org.junit.jupiter.api.Assertions.assertEquals;
44

5-
import org.junit.jupiter.api.Test;
5+
import com.thealgorithms.maths.Ceil;
6+
import org.junit.jupiter.params.ParameterizedTest;
7+
import org.junit.jupiter.params.provider.CsvSource;
68

79
public class CeilTest {
810

9-
@Test
10-
void testCeil() {
11-
assertEquals(8, Ceil.ceil(7.057));
12-
assertEquals(8, Ceil.ceil(7.004));
13-
assertEquals(-13, Ceil.ceil(-13.004));
14-
assertEquals(1, Ceil.ceil(.98));
15-
assertEquals(-11, Ceil.ceil(-11.357));
11+
@ParameterizedTest
12+
@CsvSource({"7.057, 8", "7.004, 8", "-13.004, -13", "0.98, 1", "-11.357, -11"})
13+
void testCeil(double input, int expected) {
14+
assertEquals(expected, Ceil.ceil(input));
1615
}
1716
}

0 commit comments

Comments
 (0)