www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Convertion problem

reply "lanael" <no mail.never> writes:
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 ??
Feb 17 2006
parent reply "Jarrett Billingsley" <kb3ctd2 yahoo.com> writes:
"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(); }
Feb 17 2006
parent "lanael" <no mail.never> writes:
 "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 !
Feb 18 2006