[英]How do you get a random decimal number (positive and negative) in PHP
我希望在Google地图上随机放置标记,因此希望使用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就足够了。 如果您不相信我,请在Google地图(-32.833,151.893)和(-32.832,151.895)上尝试一下,看看它们之间还有多远。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.