Puzzling rand behavior

Does anyone know why I am getting such odd results from this code, WUBBY should be always less than dimx*dimy, just as TUBBY is, but it seems when i use f32 it goes haywire, i must be doing something silly, please take a look.


use rand::Rng; // 0.8.5

fn main() {

let dimy = 2;
let dimx = 8;

let dimyy = 2f32;
let dimxx = 8f32;

let mut rng = rand::thread_rng();
for _ in 0..20{

let xx = rng.gen_range(0f32..dimxx);
let yy = rng.gen_range(0f32..dimyy);

let x = rng.gen_range(0..dimx);
let y = rng.gen_range(0..dimy);


let tubby = y * dimx + x;
let wubby = yy * dimxx + xx;

println!("MAX = {} and TUBBY = {tubby}", dimx*dimy);
println!("MAX = {} and WUBBY = {wubby}", dimxx*dimyy);

}
/*
for y in 0f32..dimy as f32 {
    for x in 0f32..dimx as f32 {
        println!("sum = {}", y*dimx+x);
        }
  }
*/  
}

(Playground)

Output:

MAX = 16 and TUBBY = 4
MAX = 16 and WUBBY = 15.100493
MAX = 16 and TUBBY = 7
MAX = 16 and WUBBY = 9.240486
MAX = 16 and TUBBY = 14
MAX = 16 and WUBBY = 13.875998
MAX = 16 and TUBBY = 7
MAX = 16 and WUBBY = 16.023575
MAX = 16 and TUBBY = 13
MAX = 16 and WUBBY = 8.096518
MAX = 16 and TUBBY = 11
MAX = 16 and WUBBY = 1.2263012
MAX = 16 and TUBBY = 8
MAX = 16 and WUBBY = 3.4603014
MAX = 16 and TUBBY = 12
MAX = 16 and WUBBY = 10.853826
MAX = 16 and TUBBY = 7
MAX = 16 and WUBBY = 10.752557
MAX = 16 and TUBBY = 6
MAX = 16 and WUBBY = 11.974583
MAX = 16 and TUBBY = 2
MAX = 16 and WUBBY = 15.234457
MAX = 16 and TUBBY = 8
MAX = 16 and WUBBY = 21.05091
MAX = 16 and TUBBY = 12
MAX = 16 and WUBBY = 12.915624
MAX = 16 and TUBBY = 10
MAX = 16 and WUBBY = 17.671871
MAX = 16 and TUBBY = 0
MAX = 16 and WUBBY = 2.4510412
MAX = 16 and TUBBY = 11
MAX = 16 and WUBBY = 2.006218
MAX = 16 and TUBBY = 12
MAX = 16 and WUBBY = 23.058807
MAX = 16 and TUBBY = 11
MAX = 16 and WUBBY = 16.039093
MAX = 16 and TUBBY = 7
MAX = 16 and WUBBY = 4.9726334
MAX = 16 and TUBBY = 11
MAX = 16 and WUBBY = 17.340086

Errors:

   Compiling playground v0.0.1 (/playground)
    Finished dev [unoptimized + debuginfo] target(s) in 0.39s
     Running `target/debug/playground`

No, the limit is WUBBY = yy * dimxx + xx < dimyy * dimxx + dimxx = 24.

2 Likes

And with TUBBY there's no such problem, since TUBBY = y * dimx + x <= (dimy - 1) * dimx + (dimx - 1) = dimy * dimx - 1.

3 Likes

Thanks guys that helps a lot

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.