如何在PHP中获得随机十进制数(正数和负数)

时间:2013-05-22 12:38:17

标签: php math coordinates

我希望在Google地图上随机定位标记,以便使用PHP随机生成标记的经度和纬度,并通过AJAX加载它们。我遇到的问题不仅是坐标小数,还有一些是负数。例如,我需要经度介于-2.07137437719725和-1.92779606909178之间,纬度介于50.71603387939352和50.793906977546456之间。我能找到的唯一随机函数只适用于正整数,因此不可行。我确实尝试将数字乘以十亿来删除小数,然后将结果随机数除以相同的数量以返回使用小数,但遗憾的是PHP无法处理如此大的数字。

我希望你能提供帮助。

由于

2 个答案:

答案 0 :(得分:1)

这是我酿造的功能。它需要一些小数点作为参数,并使用随机数偶数/奇数的检查来使积极性/消极性随机化。

    $latlon = randomLatLon(4);
    print_r($latlon);

    function randomLatLon($granularity) {

            // $granularity = Number of decimal spaces.
            $power = pow(10,$granularity); // Extended 10 to the power of $granularity.

            // Generate the lat & lon (as absolutes) according to desired granularity.
            $lat = rand(0,90 * $power) / $power;
            $lon = rand(0,180 * $power) / $power;

            // Check if a random number is even to randomly make the lat/lon negative.
            if (rand(0,100) % 2 == 0) {
                    $lat = $lat * -1;
            }

            // Same for lon...
            if (rand(0,100) % 2 == 0) {
                    $lon = $lon * -1;
            }

            return array(
                    "lat" => $lat,
                    "lon" => $lon,
            );


    }

答案 1 :(得分:0)

您可以使用以下内容:

float Latitudes = (float)((rand(0, 180000000) - 90000000)) / 1000000);
float Latitudes = (float)((rand(0, 360000000) - 180000000)) / 1000000);

就我个人而言,我认为高达0.001的准确度对于这些地点来说已经足够了。如果你不相信我,请在谷歌地图上试试(-32.833,151.893)& (-32.832,151.895),看看它们之间有多远。