Skip to content

Commit 59e980a

Browse files
committed
refactor: fix edge cases
1 parent 2b6f328 commit 59e980a

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

src/main/java/com/thealgorithms/maths/Ceil.java

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,19 @@ private Ceil() {
1616
* @return the smallest double greater than or equal to {@code number}
1717
*/
1818
public static double ceil(double number) {
19-
long intPart = (long) number;
19+
if (Double.isNaN(number) || Double.isInfinite(number) || number == 0.0 || number < Integer.MIN_VALUE || number > Integer.MAX_VALUE) {
20+
return number;
21+
}
2022

23+
if (number < 0.0 && number > -1.0) {
24+
return -0.0;
25+
}
26+
27+
long intPart = (long) number;
2128
if (number > 0 && number != intPart) {
2229
return intPart + 1.0;
2330
} else {
24-
return (double) intPart;
31+
return intPart;
2532
}
2633
}
2734
}

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

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,9 @@
44

55
import org.junit.jupiter.params.ParameterizedTest;
66
import org.junit.jupiter.params.provider.CsvSource;
7+
import org.junit.jupiter.params.provider.MethodSource;
8+
9+
import java.util.stream.Stream;
710

811
public class CeilTest {
912

@@ -12,4 +15,16 @@ public class CeilTest {
1215
void testCeil(double input, int expected) {
1316
assertEquals(expected, Ceil.ceil(input));
1417
}
18+
19+
@ParameterizedTest
20+
@MethodSource("edgeCaseProvider")
21+
void testEdgeCases(TestData data) {
22+
assertEquals(Ceil.ceil(data.input), data.expected);
23+
}
24+
25+
record TestData(double input, double expected) {}
26+
27+
static Stream<TestData> edgeCaseProvider() {
28+
return Stream.of(new TestData(Double.MAX_VALUE, Double.MAX_VALUE), new TestData(Double.MIN_VALUE, Math.ceil(Double.MIN_VALUE)), new TestData(0.0, Math.ceil(0.0)), new TestData(-0.0, Math.ceil(-0.0)), new TestData(Double.NaN, Math.ceil(Double.NaN)), new TestData(Double.NEGATIVE_INFINITY, Math.ceil(Double.NEGATIVE_INFINITY)), new TestData(Double.POSITIVE_INFINITY, Math.ceil(Double.POSITIVE_INFINITY)));
29+
}
1530
}

0 commit comments

Comments
 (0)