math: add fn clamp (#12205)

pull/12207/head^2
czkz 2021-10-17 06:42:40 +03:00 committed by GitHub
parent fd3a10ab43
commit 29f068997b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 20 additions and 0 deletions

View File

@ -87,6 +87,18 @@ pub fn minmax(a f64, b f64) (f64, f64) {
return b, a return b, a
} }
// clamp returns x constrained between a and b
[inline]
pub fn clamp(x f64, a f64, b f64) f64 {
if x < a {
return a
}
if x > b {
return b
}
return x
}
// sign returns the corresponding sign -1.0, 1.0 of the provided number. // sign returns the corresponding sign -1.0, 1.0 of the provided number.
// if n is not a number, its sign is nan too. // if n is not a number, its sign is nan too.
[inline] [inline]

View File

@ -435,6 +435,14 @@ fn test_min() {
} }
} }
fn test_clamp() {
assert clamp(2, 5, 10) == 5
assert clamp(7, 5, 10) == 7
assert clamp(15, 5, 10) == 10
assert clamp(5, 5, 10) == 5
assert clamp(10, 5, 10) == 10
}
fn test_signi() { fn test_signi() {
assert signi(inf(-1)) == -1 assert signi(inf(-1)) == -1
assert signi(-72234878292.4586129) == -1 assert signi(-72234878292.4586129) == -1