[英]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.