Thread overview
Convertion problem
Feb 17, 2006
lanael
Feb 18, 2006
lanael
February 17, 2006
I'm getting strange readings...
doing that :

--------------------8<------------------
import std.random;

void main()
{
	int i;
	float f1, f2, f3;

	for(int z=0;z<20;z++)
	{
   	i=rand()%2*2-1;		// 1 or -1 random integer

		f1=rand()%2*2-1;
		f2=cast(float)(rand()%2*2-1);
		f3=i;

		printf("%f1 \t\t %f2 \t\t %f3\n",f1,f2,f3);
	}
}
-------------------->8------------------

Looks like an overflow problem, but why ??


February 18, 2006
"lanael" <no@mail.never> wrote in message news:mn.8d3f7d621b84e8ba.35838@mail.never...
> Looks like an overflow problem, but why ??

std.random.rand() returns a uint, in the range 0 to 4billion something (that exact number that you're getting).  When you assign the result of that rand() expression to an int, it gets converted to a signed integer.  But when you put it in a float, the float is big enough to hold that number and so it gets stored that way.

If you replace rand() with (cast(int)rand()), the problem goes away.  Of course, that looks ugly, so you could make a function for it, like

int intRand()
{
    return cast(int)rand();
}


February 18, 2006
> "lanael" <no@mail.never> wrote in message news:mn.8d3f7d621b84e8ba.35838@mail.never...
>> Looks like an overflow problem, but why ??
>
> std.random.rand() returns a uint, 

ah yes ! I overlooked that fact...
it's obvious now, thanks !