2015-11-13 41 views
1

我有以下方法將GPS座標作爲字符串並將它們轉換爲最多6個小數點的雙精度。現在我試圖從小數點後的第一位開始隨機化小數點。隨機化一個雙精度的小數部分

public void randomizeCoordinate(String latString, String lonString) 
{ 
    double lat = Double.parseDouble(latString); 
    double lon = Double.parseDouble(lonString); 

    DecimalFormat df = new DecimalFormat("#.######"); 
    df.setRoundingMode(RoundingMode.HALF_EVEN); 
    for (Number n : Arrays.asList(lat, lon)) 
    { 
     Double d = n.doubleValue(); 
     System.out.println(df.format(d)); 
    } 
} 

例如,如果我有2.34我要的隨機分配是這樣的2.493473或2.294847或2.346758

第一個小數點在這種情況下是從2.34 3只改變最大的一個數字。向上或向下隨機。前導小數點可以隨機更改爲任何內容。

這樣做的最好方法是什麼?

回答

1
Random rand = new Random(); 
double x = ...; 

x = ((int)(x*10) + rand.nextDouble()*2 - 1)/10.0; 

乘以10和截斷以獲得數字包括第一小數,加-1和1之間的隨機數,縮減。

請注意,您的雙打不會有隻有6位十進制數字;這些數字不是十進制數字。對於輸出顯示6位小數,您需要使用請求6位十進制數字的格式來格式化數字。

0

您可以在-100,000和100,000之間找到一個隨機數,將它除以1,000,000,然後將其添加到您的原始數字。

它可以有效地使您的數字達到+0.1或-0.1的不同,但理論上可以返回0,這會導致相同的數字。

0

使用Math.random(),或java.util.Random子類...

d += 0.1 * (Math.random() * 2 - 1); 

這會給你一個範圍從2.24到2.44的例子。

如果你真的想要的範圍從2.20到2.39999999 ...,請參閱@ laune的回答。

+0

嗯,你在範圍-0.01 .. 0.01添加值以下。你最好解決這個問題。 – laune

+0

修復了,謝謝。當然,我們的答案中任何一個都假定「領先」真的意味着「拖尾」。 – david

0

下面的代碼將得到最大和最小範圍爲double你已經進入,併產生另一個隨機decimal部分,然後將其添加到原數的int一部分。

// Example double 
    double lat = Double.parseDouble("2.59"); 

    // Get the first decimal place 
    // http://stackoverflow.com/questions/8164487/getting-the-first-decimal-place-of-a-number 
    int first_dec = ((int)(Math.floor(Math.abs(lat) * 10))) % 10; 

    // Get the min and max range 
    double min = (double)(first_dec - 1)/10; 
    double max = (double)(first_dec + 1)/10; 

    // Generate a random number in that range 
    Random rand = new Random(); 
    double randomValue = min + (max - min) * rand.nextDouble(); 

    // Printing for clarifying 
    System.out.println("min = " + min + " : max = " + max + " : randomValue = " + randomValue); 

    // Format as required 
    DecimalFormat df = new DecimalFormat("#.######"); 
    System.out.println(df.format((int)lat + randomValue)); 

對於例如雙(2.59),這產生在多個運行

min = 0.4 : max = 0.6 : randomValue = 0.5189434537923328 
2.518943 
min = 0.4 : max = 0.6 : randomValue = 0.5283024116190669 
2.528302 
min = 0.4 : max = 0.6 : randomValue = 0.44384090285085204 
2.443841