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


How do you get a random decimal number (positive and negative) in PHP

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

我希望你能帮忙。

感谢保罗

我编写了一个函数来完成这个任务。它以一些小数点作为参数,并使用偶数/奇数的随机数检查来使正负随机化。

    $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,
            );

    }

你可以这样写:

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),看看它们之间有多远