...

View Full Version : Rand Number



Creekynoise
07-16-2008, 03:49 AM
I need a script that will generate a random number between -.5 and +.05

I've tried this:


$num = rand(-.05, .05);
print ("$num");

but it hasn't worked..

kbluhm
07-16-2008, 03:57 AM
$num = mt_rand( -5, 5 ) / 10;

Fou-Lu
07-16-2008, 04:08 AM
Gotta tell them why mate, otherwise nobody learns anything :P

rand function require integer results. 0.5 and -0.5 are equal to 0, so you'll never receive a correct number. Instead, as kblumm used seek between 5 and -5 and divide you're result by 10. Don't forget to divide by 10.0 - otherwise you're result will be a 0.

Creekynoise
07-16-2008, 04:10 AM
$num = mt_rand( -5, 5 ) / 10;
print ("$num");

That didn't work either =/

Edit: Tried flipping the -5 and 5 around too..still get an error..

kbluhm
07-16-2008, 04:47 AM
No error here, copied/pasted your latest code directly and it works every time.

Creekynoise
07-16-2008, 05:11 AM
Ok it works for me now, I tried it in a new file..I guess some other code was conflicting with it, but it works, thanks!

kochier
07-16-2008, 05:12 AM
$num = mt_rand( -5, 5 ) / 10;
print ("$num");

That didn't work either =/

Edit: Tried flipping the -5 and 5 around too..still get an error..

Well what's the error?

EDIT: Nevermind, guess it's working.

rafiki
07-16-2008, 02:15 PM
Don't forget to divide by 10.0 - otherwise you're result will be a 0.

Did you miss this post? divide by 10.0

kbluhm
07-16-2008, 02:44 PM
Did you miss this post? divide by 10.0
Did you miss this post? Here it is again:

No error here, copied/pasted your latest code directly and it works every time.
This one too:

Ok it works for me now, I tried it in a new file..I guess some other code was conflicting with it, but it works, thanks!
Not sure why the suggestion was made to divide by a float, it is unnecessary.

Fou-Lu
07-16-2008, 09:35 PM
PHP is a datatype weak language. Theoretically 5 / 10 should result in 0, not in 0.5 since both of the datatypes provided are integers. PHP however attempts to find the closest matching datatype. This is actually a problem in PHP since it requires the developer to make consistency checks on all of their results. Should you ever land on a $x % 10 = 0 number, you will have an end result that is a integer, not a double. float 0 !== int 0, which forces checks on 0, not 0.0, or explicit casting to float/double. This destroys the integrity of you're variable data as you no longer know what datatype it contains.

Choosing to divide by 10.0 implicitly casts to a float, so even an $y = %x % 10 = 0 number will result in a float($y). You can always fit an integer into a float, but you can never fit a float into an integer. Try doing this in a datatype strong language like C/C++, java, C# etc. and you'll see what I'm talking about.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum