Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP random - exluding/include/floats/negatives and other animals

I need to generate a random pairs of numbers (floats) , within a certain range . Basically those are points for [Lat,Lng] pairs (Longitude - latitude coordinates)

I thought This would be very straight forward with

<?php echo (rand(0,60).'.'.rand(0,99999999999999).' ||  '); // yes, a string is ok...?>

but it did not give me the control over how many numbers after the float point (resolution) - which I need fixed.

So the next phase was :

<?php echo (rand(0,60*pow(10,6)))/pow(10,6).' ||  '; //pow(10,$f) where $ is the resolution ?>

and this works . sort of .. sometimes it produces results like

22.212346 ||  33.134 ||  36.870757 ||  //(rare , but does happen)

but hey - coordinates are from -90 to 90 (lon) and -180 to 180 (lan) - what about the minus ?

echo (rand(0,-180*pow(10,9)))/pow(10,9).' ||  ';

that should do it .. and combining all together should give me somehow a random string like

23.0239423525 || -135.937419777

so after all this introduction - here is Are my question(s) .

  • Being the newbie that I am - am I missing something ? is there no built-in function to generate random floats with a negative to positive range in PHP ?

  • Why is the function above sometimes turns only resolution 3,4 or 5 if it is told to return 6 (i did not apply any ABS or ROUND) - is there an automatic rounding in php ? and if there is , how to avoid it ?

  • I have noticed that the "random" is not so random - the generated numbers are always more or less series between a range - close to one another . is the PHP random a simple very-very-very fast rotating counter ?

  • how do I EXCLUDE a range from this generated range ?? (or actually and array of ranges)

I know these are a lot of questions, but any help / thought would be great ! (and if the first one is answered positively, the rest can almost be ignored :-)

like image 678
Obmerk Kronen Avatar asked Oct 23 '22 06:10

Obmerk Kronen


1 Answers

The rand() function can take a negative min so maybe you can do this:

   $num = mt_rand(-180000000, 180000000)/1000000;
   echo number_format($num, 6);

if you want 6 places after decimal point.

In terms of excluding a range you may have to do it in two steps. First consider the ranges that you do want. Lets say you have 3 ranges from which you want to generate the random number. range 1 = -180 to -10, range 2 = 10 - 100 and range 3 = 120 - 180. Then you can generate a random number from 1 to 3 inclusive, use that to pick one range and then generate the number in that range.

like image 120
Vincent Ramdhanie Avatar answered Nov 03 '22 04:11

Vincent Ramdhanie