views:

51

answers:

3

how can I regenerate random decimal from -0.0010 to 0.0010 with php rand()? or any other?

+1  A: 

.

$val = (rand(0,20)-10)/10000;
nathan
Now you've really limited to 21 possible values. But perhaps that's what benmsia wants...
VolkerK
yeah. thx. tho more values generated will be better but if there's no valid solution then i will stick to this temporarily till a new solution is found. thanks nathan.
benmsia
+1  A: 

This will return any possible number between -0.001 and +0.001

$random = ((rand()*(0.002/getrandmax()))-0.001)
// or without paranthesis:
$random = rand()*0.002/getrandmax()-0.001
jigfox
You don't need all these brackets.
Harmen
Yeah sure, but they don't hurt either
jigfox
@jens, hi thanks for your input. but it generated a -ve 2.plus value for unknown reason. you have any idea?
benmsia
what do you mean by "a -ve 2.plus value"
jigfox
+2  A: 

Devide rand() by the maximum rand-numer, multiply it by the range and add the starting number:

<?php
  // rand()/getrandmax() gives a float number between 0 and 1
  // if you multiply it by 0.002 you'll get a number between 0 and 0.002
  // add the starting number -0.001 and you'll get a number between -0.001 and 0.001

  echo rand()/getrandmax()*0.002-0.001;
?>
Harmen
Hi Harmen, don't know what reason fomr ur formula i have found a bug there. it generated a -ve 2.plus value.. u have any idea? thanks
benmsia
I guess you found a number close to zero, like `-4.7090060121464E-5`. It means `-4.7*10^-5` which is `-0.000047`
Harmen