Skip to content

Commit 65aa43f

Browse files
authored
feat: Add signum (TheAlgorithms#419)
1 parent 560aa2b commit 65aa43f

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

Diff for: src/math/mod.rs

+2
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ mod prime_numbers;
3131
mod quadratic_residue;
3232
mod random;
3333
mod sieve_of_eratosthenes;
34+
mod signum;
3435
mod simpson_integration;
3536
mod square_root;
3637
mod trial_division;
@@ -76,6 +77,7 @@ pub use self::prime_numbers::prime_numbers;
7677
pub use self::quadratic_residue::cipolla;
7778
pub use self::random::PCG32;
7879
pub use self::sieve_of_eratosthenes::sieve_of_eratosthenes;
80+
pub use self::signum::signum;
7981
pub use self::simpson_integration::simpson_integration;
8082
pub use self::square_root::{fast_inv_sqrt, square_root};
8183
pub use self::trial_division::trial_division;

Diff for: src/math/signum.rs

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/// Signum function is a mathematical function that extracts
2+
/// the sign of a real number. It is also known as the sign function,
3+
/// and it is an odd piecewise function.
4+
/// If a number is negative, i.e. it is less than zero, then sgn(x) = -1
5+
/// If a number is zero, then sgn(0) = 0
6+
/// If a number is positive, i.e. it is greater than zero, then sgn(x) = 1
7+
8+
pub fn signum(number: f64) -> i8 {
9+
if number == 0.0 {
10+
return 0;
11+
} else if number > 0.0 {
12+
return 1;
13+
}
14+
15+
-1
16+
}
17+
18+
#[cfg(test)]
19+
mod tests {
20+
use super::*;
21+
22+
#[test]
23+
fn positive_integer() {
24+
assert_eq!(signum(15.0), 1);
25+
}
26+
27+
#[test]
28+
fn negative_integer() {
29+
assert_eq!(signum(-30.0), -1);
30+
}
31+
32+
#[test]
33+
fn zero() {
34+
assert_eq!(signum(0.0), 0);
35+
}
36+
}

0 commit comments

Comments
 (0)