Skip to content

Commit 1c37c24

Browse files
authored
fix math/ceil function for issue TheAlgorithms#423 (TheAlgorithms#424)
1 parent 65aa43f commit 1c37c24

File tree

1 file changed

+16
-4
lines changed

1 file changed

+16
-4
lines changed

src/math/ceil.rs

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,11 @@
22
// Source: https://en.wikipedia.org/wiki/Floor_and_ceiling_functions
33

44
pub fn ceil(x: f64) -> f64 {
5-
let x_round = x.round();
6-
if (x_round * 10.0).round() < (x * 10.0).round() {
7-
x_round + 1.0
5+
let x_rounded_towards_zero = x as i32 as f64;
6+
if x < 0. || x_rounded_towards_zero == x {
7+
x_rounded_towards_zero
88
} else {
9-
x_round
9+
x_rounded_towards_zero + 1_f64
1010
}
1111
}
1212

@@ -20,6 +20,12 @@ mod tests {
2020
assert_eq!(ceil(num), num.ceil());
2121
}
2222

23+
#[test]
24+
fn positive_decimal_with_small_number() {
25+
let num = 3.01;
26+
assert_eq!(ceil(num), num.ceil());
27+
}
28+
2329
#[test]
2430
fn positive_integer() {
2531
let num = 1.00;
@@ -32,6 +38,12 @@ mod tests {
3238
assert_eq!(ceil(num), num.ceil());
3339
}
3440

41+
#[test]
42+
fn negative_decimal_with_small_number() {
43+
let num = -1.01;
44+
assert_eq!(ceil(num), num.ceil());
45+
}
46+
3547
#[test]
3648
fn negative_integer() {
3749
let num = -1.00;

0 commit comments

Comments
 (0)