Obmerk Kronen
Obmerk Kronen

Reputation: 15949

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) .

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 :-)

Upvotes: 5

Views: 608

Answers (1)

Vincent Ramdhanie
Vincent Ramdhanie

Reputation: 103135

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.

Upvotes: 3

Related Questions