forked from TheAlgorithms/Rust
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: Add signum (TheAlgorithms#419)
- Loading branch information
1 parent
560aa2b
commit 65aa43f
Showing
2 changed files
with
38 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
/// Signum function is a mathematical function that extracts | ||
/// the sign of a real number. It is also known as the sign function, | ||
/// and it is an odd piecewise function. | ||
/// If a number is negative, i.e. it is less than zero, then sgn(x) = -1 | ||
/// If a number is zero, then sgn(0) = 0 | ||
/// If a number is positive, i.e. it is greater than zero, then sgn(x) = 1 | ||
pub fn signum(number: f64) -> i8 { | ||
if number == 0.0 { | ||
return 0; | ||
} else if number > 0.0 { | ||
return 1; | ||
} | ||
|
||
-1 | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use super::*; | ||
|
||
#[test] | ||
fn positive_integer() { | ||
assert_eq!(signum(15.0), 1); | ||
} | ||
|
||
#[test] | ||
fn negative_integer() { | ||
assert_eq!(signum(-30.0), -1); | ||
} | ||
|
||
#[test] | ||
fn zero() { | ||
assert_eq!(signum(0.0), 0); | ||
} | ||
} |