diff libinterp/corefcn/rand.cc @ 17258:213ee68b59da

Handle out-of-range values consistently when initializing random number generator. * oct-rand.cc: New function double2uint32(). It normalizes a finite double by taking it modulo 2^32, such that the result is in [0, 2^32). Nonfinites give zero as result. This prevents compiler-dependent casting of a double whose truncated value cannot be represented in a uint32_t. * rand.cc: Add %!test block to verify behavior.
author Philipp Kutin <philipp.kutin@gmail.com>
date Thu, 15 Aug 2013 20:14:30 +0200
parents 2fc554ffbc28
children bc924baa2c4e
line wrap: on
line diff
--- a/libinterp/corefcn/rand.cc	Thu Aug 15 14:17:20 2013 -0700
+++ b/libinterp/corefcn/rand.cc	Thu Aug 15 20:14:30 2013 +0200
@@ -533,6 +533,19 @@
 %! endif
 */
 
+/*
+%!# Test out-of-range values as rand() seeds.  See oct-rand.cc: double2uint32().
+%!function v = __rand_sample__ (initval)
+%!  rand ("state", initval);
+%!  v = rand (1, 6);
+%!endfunction
+%!
+%!assert (__rand_sample__ (0), __rand_sample__ (2^32))
+%!assert (__rand_sample__ (-2), __rand_sample__ (2^32-2))
+%!assert (__rand_sample__ (Inf), __rand_sample__ (NaN))
+%!assert (! isequal (__rand_sample__ (-1), __rand_sample__ (-2)))
+*/
+
 static std::string current_distribution = octave_rand::distribution ();
 
 DEFUN (randn, args, ,