Very strange? Code generation bug?

Tom S h3r3tic at -remove-.mat.uni.torun.pl
Tue Apr 11 16:51:44 PDT 2006


Ivan Senji wrote:
> float random1()
> {
>   float f = rand()%101;
>   return (f-50)/50;
> }

This is what happens:
1. rand() returns a random uint. It gets warped in the range 0 .. 100
2. the uint from 0 .. 100 is stored into a float
3. you subtract 50 and divide by 50. everything is fine.

> float random2()
> {
>   return (rand()%101-50)/50;
> }

This is what happens:
1. rand() returns a random uint. It gets warped in the range 0-100
2. you subtract 50 from the uint in range 0 .. 100, thus possibly 
wrapping it around its 0xffffffff boundary, thus getting an uint in 
range (0xffffffff - 50) .. 50
3. you divide the uint by 50, thus yielding a very big number if it were 
from the range (0xffffffff - 50) .. 0xffffffff or 1 if it were 50 or 0 
if it were from the range 0 .. 49


Hope this helps :)


-- 
-----BEGIN GEEK CODE BLOCK-----
Version: 3.1
GCS/M d-pu s+: a-->----- C+++$>++++ UL P+ L+ E--- W++ N++ o? K? w++ !O 
!M V? PS- PE- Y PGP t 5 X? R tv-- b DI- D+ G e>+++ h>++ !r !y
------END GEEK CODE BLOCK------

Tomasz Stachowiak  /+ a.k.a. h3r3tic +/



More information about the Digitalmars-d-bugs mailing list