ref: 607b2662bc1093833bfea0c49236f098271cf348
parent: 288e48ee60b049206d1dd8ce250bf09c92452e7b
author: Ori Bernstein <[email protected]>
date: Mon Dec 14 17:02:55 EST 2015
Fix libstd rng for unsigned vlaues, and add tests.
--- a/lib/std/rand.myr
+++ b/lib/std/rand.myr
@@ -1,4 +1,5 @@
use "die.use"
+use "extremum.use"
use "assert.use"
use "types.use"
use "alloc.use"
@@ -113,11 +114,11 @@
var maxrand
var val
- assert(hi - lo > 0, "rand.myr: range for random values must be >= 1")
+ span = abs(hi - lo)
+ assert(span > 0, "rand.myr: range for random values must be >= 1, got hi={}, lo={}\n", hi, lo)
- span = hi - lo
- maxrand = (1 << (8*sizeof(@a))) - 1 /* max for signed value */
- if maxrand < 0 /* signed */
+ maxrand = ~0
+ if maxrand < 0 /* if we're signed the maximum value is different */
maxrand = (1 << (8*sizeof(@a)-1)) - 1 /* max for signed value */
;;
--- /dev/null
+++ b/lib/std/test/rand.myr
@@ -1,0 +1,45 @@
+use std
+
+const main = {
+ var v32, t32 : int32
+ var vu64, tu64 : uint64
+ var allsame
+
+ /* basic int32 */
+ allsame = true
+ v32 = std.rand(0, 666)
+ for var i = 0; i < 128; i++
+ t32 = std.rand(0, 666)
+ std.assert(t32 >= 0 && t32 < 666, "value {} is out of range [0, 666)\n", t32)
+ if t32 != v32
+ allsame = false
+ ;;
+ ;;
+ std.assert(!allsame, "all values generated were identical.\n")
+
+
+ /* negative range */
+ allsame = true
+ v32 = std.rand(-888, -111)
+ for var i = 0; i < 128; i++
+ t32 = std.rand(-888, -111)
+ std.assert(t32 >= -888 && t32 < -111, "value {} is out of range [-888, -111)\n", t32)
+ if t32 != v32
+ allsame = false
+ ;;
+ ;;
+ std.assert(!allsame, "all values generated were identical.\n")
+
+
+ /* basic uint64 */
+ allsame = true
+ vu64 = std.rand(0, 88)
+ for var i = 0; i < 128; i++
+ tu64 = std.rand(0, 88)
+ std.assert(tu64 >= 0 && tu64 < 666, "value {} is out of range [0, 88)\n", tu64)
+ if tu64 != vu64
+ allsame = false
+ ;;
+ ;;
+ std.assert(!allsame, "all values generated were identical.\n")
+}