rand: add random functions for f32 and f64, [0,max] and [min,max] versions

pull/5075/head
Larpon 2020-05-27 15:41:37 +02:00 committed by GitHub
parent e0db880791
commit 8c753ddf8d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 69 additions and 0 deletions

View File

@ -23,3 +23,25 @@ pub fn rand_r(seed &int) int {
}
return ns & 0x7fffffff
}
// rand_f32 return a random f32 between 0 and max
pub fn rand_f32(max f32) f32 {
return f32( f64(C.rand()) / ( f64(C.RAND_MAX)/f64(max) ) )
}
// rand_f32 return a random f32 in range min and max
pub fn rand_f32_in_range(min f32, max f32) f32 {
scaled_r := f32(rand.next( 2147483647 )) / 2147483647.0
return min + scaled_r * (max - min )
}
// rand_f64 return a random f64 between 0 and max
pub fn rand_f64(max f32) f32 {
return f64(C.rand()) / ( f64(C.RAND_MAX)/f64(max) )
}
// rand_f64 return a random f64 in range min and max
pub fn rand_f64_in_range(min f64, max f64) f64 {
scaled_r := f64(rand.next( 2147483647 )) / 2147483647.0
return min + scaled_r * (max - min )
}

View File

@ -56,3 +56,50 @@ fn assert_randoms_equal(r1, r2 []int) {
assert r1[i] == r2[i]
}
}
fn test_rand_f32() {
mut prev_res := f32(-1.0)
for _ in 0..rnd_count+1 {
res := rand.rand_f32(1.0)
assert res >= 0.0
assert res <= 1.0
prev_res = res
}
}
fn test_rand_f32_in_range() {
for _ in 0..rnd_count+1 {
res := rand.rand_f32_in_range(1.0,2.0)
assert res >= 1.0
assert res <= 2.0
// NOTE assert res != prev_res
// ^- this kind of test can and WILL fail. Random numbers can be the same in subsequent runs
}
}
fn test_rand_f64() {
for _ in 0..rnd_count+1 {
res := rand.rand_f64(1.0)
assert res >= 0.0
assert res <= 1.0
}
}
fn test_rand_f64_in_range() {
for _ in 0..rnd_count {
res := rand.rand_f64_in_range(1.0,2.0)
assert res >= 1.0
assert res <= 2.0
}
}