簡體   English   中英

在 Java 中獲取隨機布爾值

[英]Get random boolean in Java

好的,我在我的代碼中實現了這個 SO 問題: Return True or False Randomly

但是,我有一個奇怪的行為:我需要同時運行十個實例,每個實例每次運行只返回一次 true 或 false。 令人驚訝的是,無論我做什么,每次我都是false

有什么方法可以改進該方法,以便我至少有大約 50% 的機會成為true嗎?


為了讓它更容易理解:我將我的應用程序構建為 JAR 文件,然后通過批處理命令運行

 java -jar my-program.jar
 pause

程序的內容——盡可能簡單:

public class myProgram{

    public static boolean getRandomBoolean() {
        return Math.random() < 0.5;
        // I tried another approaches here, still the same result
    }

    public static void main(String[] args) {
        System.out.println(getRandomBoolean());  
    }
}

如果我打開 10 個命令行並運行它,結果每次都是false ...

我推薦使用Random.nextBoolean()

話雖如此,您使用的Math.random() < 0.5也有效。 這是我機器上的行為:

$ cat myProgram.java 
public class myProgram{

   public static boolean getRandomBoolean() {
       return Math.random() < 0.5;
       //I tried another approaches here, still the same result
   }

   public static void main(String[] args) {
       System.out.println(getRandomBoolean());  
   }
}

$ javac myProgram.java
$ java myProgram ; java myProgram; java myProgram; java myProgram
true
false
false
true

不用說,不能保證每次都能得到不同的值。 但是,就您而言,我懷疑

A)你沒有使用你認為的代碼,(比如編輯錯誤的文件)

B)你沒有在測試時編譯你的不同嘗試,或者

C)您正在使用一些非標准的損壞實現。

您是否嘗試過查看Java 文檔

從該隨機數生成器的序列中返回下一個偽隨機、均勻分布的布爾值……值truefalse以(近似)相等的概率生成。

例如:

import java.util.Random;

Random random = new Random();
random.nextBoolean();

您也可以嘗試nextBoolean() -Method

這是一個例子: http ://www.tutorialspoint.com/java/util/random_nextboolean.htm

Java 8 :使用與當前線程隔離的隨機生成器: ThreadLocalRandom nextBoolean()

與 Math 類使用的全局 Random 生成器一樣,ThreadLocalRandom 使用內部生成的種子進行初始化,否則可能無法修改。 適用時,在並發程序中使用 ThreadLocalRandom 而不是共享 Random 對象通常會遇到更少的開銷和爭用。

java.util.concurrent.ThreadLocalRandom.current().nextBoolean();

為什么不使用Random類,它有一個方法nextBoolean

import java.util.Random;

/** Generate 10 random booleans. */
public final class MyProgram {

  public static final void main(String... args){

    Random randomGenerator = new Random();
    for (int idx = 1; idx <= 10; ++idx){
      boolean randomBool = randomGenerator.nextBoolean();
      System.out.println("Generated : " + randomBool);
    }
  }
}

您可以使用以下方法獲得無偏見的結果:

Random random = new Random();
//For 50% chance of true
boolean chance50oftrue = (random.nextInt(2) == 0) ? true : false;

注意: random.nextInt(2) 表示數字 2 是邊界。 計數從 0 開始。所以我們有 2 個可能的數字(0 和 1),因此概率是 50%!

如果你想給你的結果更多的概率是真的(或假的)你可以調整上面的如下!

Random random = new Random();

//For 50% chance of true
boolean chance50oftrue = (random.nextInt(2) == 0) ? true : false;

//For 25% chance of true
boolean chance25oftrue = (random.nextInt(4) == 0) ? true : false;

//For 40% chance of true
boolean chance40oftrue = (random.nextInt(5) < 2) ? true : false;

初始化隨機數生成器的最簡單方法是使用無參數構造函數,例如

Random generator = new Random();

但是,在使用此構造函數時,您應該認識到算法隨機數生成器並不是真正隨機的,它們實際上是生成固定但看起來隨機的數字序列的算法。

您可以通過為 Random 構造函數提供“種子”參數使其看起來更“隨機”,您可以動態構建該參數,例如使用以毫秒為單位的系統時間(它總是不同的)

你可以獲得你的 clock() 值並檢查它是奇數還是偶數。 我不知道它是否是 %50 of true

您可以自定義創建您的隨機函數:

static double  s=System.nanoTime();//in the instantiating of main applet
public static double randoom()
{

s=(double)(((555555555* s+ 444444)%100000)/(double)100000);


    return s;
}

數字 55555.. 和 444.. 是獲得廣泛功能的大數字,請忽略 Skype 圖標:D

您還可以制作兩個隨機整數並驗證它們是否相同,這使您可以更好地控制概率。

Random rand = new Random();

聲明一個范圍來管理隨機概率。 在此示例中,有 50% 的可能性為真。

int range = 2;

生成 2 個隨機整數。

int a = rand.nextInt(range);
int b = rand.nextInt(range);

然后簡單比較返回值。

return a == b; 

我也有一個你可以使用的課程。 隨機范圍.java

文本中的單詞總是隨機性的來源。 給定一個詞,無法推斷出下一個詞。 對於每個單詞,我們可以獲取其字母的 ASCII 代碼,將這些代碼相加形成一個數字。 這個數字的奇偶性是隨機布爾值的一個很好的候選者。

可能的缺點:

  1. 該策略基於使用文本文件作為單詞的來源。 在某個時候,將到達文件的末尾。 但是,您可以估計預計從您的應用中調用 randomBoolean() 函數的次數。 如果您需要調用它大約 100 萬次,那么一個包含 100 萬個單詞的文本文件就足夠了。 作為更正,您可以使用來自實時源(如在線報紙)的數據流。

  2. 通過對一種語言中的常用短語和成語進行一些統計分析,可以在給定短語的第一個單詞的情況下,以一定程度的准確性估計短語中的下一個單詞。 但從統計上看,當我們可以准確預測下一個單詞時,這些情況很少見。 所以,在大多數情況下,下一個詞獨立於前一個詞。

    包p01;

    導入java.io.文件; 導入 java.nio.file.Files; 導入 java.nio.file.Paths;

    公共課主要{

     String words[]; int currentIndex=0; public static String readFileAsString()throws Exception { String data = ""; File file = new File("the_comedy_of_errors"); //System.out.println(file.exists()); data = new String(Files.readAllBytes(Paths.get(file.getName()))); return data; } public void init() throws Exception { String data = readFileAsString(); words = data.split("\\t| |,|\\.|'|\\r|\\n|:"); } public String getNextWord() throws Exception { if(currentIndex>words.length-1) throw new Exception("out of words; reached end of file"); String currentWord = words[currentIndex]; currentIndex++; while(currentWord.isEmpty()) { currentWord = words[currentIndex]; currentIndex++; } return currentWord; } public boolean getNextRandom() throws Exception { String nextWord = getNextWord(); int asciiSum = 0; for (int i = 0; i < nextWord.length(); i++){ char c = nextWord.charAt(i); asciiSum = asciiSum + (int) c; } System.out.println(nextWord+"-"+asciiSum); return (asciiSum%2==1); } public static void main(String args[]) throws Exception { Main m = new Main(); m.init(); while(true) { System.out.println(m.getNextRandom()); Thread.sleep(100); } }

    }

在 Eclipse 中,在我項目的根目錄中,有一個名為“the_comedy_of_errors”的文件(無擴展名)- 使用“文件”>“新建”>“文件”創建,我從此處粘貼了一些內容:http://shakespeare.mit.edu/comedy_errors /comedy_errors.1.1.html

對於靈活的布爾隨機數發生器:

public static rbin(bias){
    bias = bias || 50;
    return(Math.random() * 100 <= bias);
    /*The bias argument is optional but will allow you to put some weight
      on the TRUE side. The higher the bias number, the more likely it is
      true.*/
}

確保使用數字0 - 100 ,否則您可能會降低偏差並獲得更常見的false值。

PS:除了 Java 與 JavaScript 有一些共同點外,我對 Java 一無所知。 我使用我的 JavaScript 知識加上我的推理能力來構建這段代碼。 希望我的回答不起作用。 你們都可以編輯這個答案來解決我不知道的任何問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM