Very strange? Code generation bug?

Dave Dave_member at pathlink.com
Tue Apr 11 18:46:00 PDT 2006


Ivan Senji wrote:
> with this program:
> 
> <code>
> import std.stdio;
> import std.random;
> 
> float random1()
> {
>   float f = rand()%101;
>   return (f-50)/50;
> }
> 
> float random2()
> {
>   return (rand()%101-50)/50;
> }
> 
> void main()
> {
>   for(int i=0;i<10;i++)
>   {
>     writef(random1(), " ");
>   }
> 
>   writefln("\n");
> 
>   for(int i=0;i<10;i++)
>   {
>     writef(random2(), " ");
>   }
> }
> </code>
> 
> i get output something like (Windows XP, DMD 0.153):
> 
> 0.4 0.28 -0.46 0.2 0.48 0.7 -0.7 -0.18 -0.56 0.2
> 
> 0 8.58993e+07 8.58993e+07 0 8.58993e+07 8.58993e+07 0 0 0 0
> 
> 
> The problem is both functions random1 and random2 should be returning a
> number between -1 and 1 and they are doing the same calculation, but
> there is something wrong with random2.
> 
> Can someone please confirm this?

Give this a shot:

;---

import std.stdio;
import std.random;

float random1()
{
   float f = rand()%101;
   return (f-50)/50;
}

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

void main()
{
   rand_seed(10,10);
   for(int i=0;i<10;i++)
   {
     writef(random1(), " ");
   }

   writefln("\n");

   rand_seed(10,10);
   for(int i=0;i<10;i++)
   {
     writef(random2(), " ");
   }

   writefln("\n");
}



More information about the Digitalmars-d-bugs mailing list