From 8c753ddf8dfbf2f17e717597fc231977449ec53f Mon Sep 17 00:00:00 2001 From: Larpon Date: Wed, 27 May 2020 15:41:37 +0200 Subject: [PATCH] rand: add random functions for f32 and f64, [0,max] and [min,max] versions --- vlib/rand/rand.v | 22 +++++++++++++++ vlib/rand/random_numbers_test.v | 47 +++++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+) diff --git a/vlib/rand/rand.v b/vlib/rand/rand.v index bc563c84ba..c6d478766a 100644 --- a/vlib/rand/rand.v +++ b/vlib/rand/rand.v @@ -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 ) +} \ No newline at end of file diff --git a/vlib/rand/random_numbers_test.v b/vlib/rand/random_numbers_test.v index 2655964b1e..caa073dd54 100644 --- a/vlib/rand/random_numbers_test.v +++ b/vlib/rand/random_numbers_test.v @@ -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 + } +}