Java에서 임의의 부울 가져 오기
좋아, 나는이 질문을 내 코드에 구현했다 : 무작위로 True 또는 False 반환
하지만 이상한 동작이 있습니다. 10 개의 인스턴스를 동시에 실행해야하는데, 모든 인스턴스가 실행 당 한 번만 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) 일부 비표준 깨진 구현으로 작업하고 있습니다.
nextBoolean()-Method 시도해 볼 수도 있습니다
. 예는 다음과 같습니다. http://www.tutorialspoint.com/java/util/random_nextboolean.htm
Sun의 (oracle) 문서를 보려고 했습니까?
http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Random.html#nextBoolean ()
어쨌든 여기에 예제 코드가 있습니다.
java.util.Random
Random random = new Random();
random.nextBoolean();
Java 8 : 현재 스레드에 격리 된 임의 생성기 사용 : ThreadLocalRandom nextBoolean ()
Math 클래스에서 사용하는 전역 Random 생성기와 마찬가지로 ThreadLocalRandom은 수정되지 않은 내부 생성 시드로 초기화됩니다. 적용 가능한 경우 동시 프로그램에서 공유 된 Random 개체 대신 ThreadLocalRandom을 사용하면 일반적으로 훨씬 적은 오버 헤드와 경합이 발생합니다.
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 generator = new Random();
그러나이 생성자를 사용할 때 알고리즘 난수 생성기는 진정한 무작위가 아니라 실제로는 고정되었지만 무작위로 보이는 일련의 숫자를 생성하는 알고리즘임을 인식해야합니다.
Random 생성자에 'seed'매개 변수를 제공하여 더 '무작위'로 보이게 만들 수 있습니다. 예를 들어 시스템 시간 (항상 달라짐)을 사용하여 동적으로 빌드 할 수 있습니다.
clock () 값을 얻고 홀수인지 짝수인지 확인할 수 있습니다. 사실의 50 %인지 모르겠습니다.
그리고 임의 함수를 사용자 정의 할 수 있습니다.
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 ..는 광범위한 기능을 얻기위한 큰 숫자입니다. 스카이프 아이콘을 무시하십시오. : D
또한 두 개의 임의의 정수를 만들고 동일한 지 확인할 수 있습니다. 이렇게하면 확률을 더 잘 제어 할 수 있습니다.
Random rand = new Random();
무작위 확률을 관리 할 범위를 선언합니다. 이 예에서는 사실 일 확률이 50 %입니다.
int range = 2;
2 개의 임의의 정수를 생성합니다.
int a = rand.nextInt(range);
int b = rand.nextInt(range);
그런 다음 값을 반환하기 만하면됩니다.
return a == b;
나는 또한 당신이 사용할 수있는 수업이 있습니다. RandomRange.java
편향되지 않은 결과를 위해 다음을 사용할 수 있습니다.
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;
텍스트의 단어는 항상 임의성의 원천입니다. 특정 단어가 주어지면 다음 단어에 대해 유추 할 수 없습니다. 각 단어에 대해 문자의 ASCII 코드를 가져 와서 해당 코드를 추가하여 숫자를 만들 수 있습니다. 이 숫자의 패리티는 임의의 부울에 대한 좋은 후보입니다.
가능한 단점 :
this strategy is based upon using a text file as a source for the words. At some point, the end of the file will be reached. However, you can estimate how many times you are expected to call the randomBoolean() function from your app. If you will need to call it about 1 million times, then a text file with 1 million words will be enough. As a correction, you can use a stream of data from a live source like an online newspaper.
using some statistical analysis of the common phrases and idioms in a language, one can estimate the next word in a phrase, given the first words of the phrase, with some degree of accuracy. But statistically, these cases are rare, when we can accuratelly predict the next word. So, in most cases, the next word is independent on the previous words.
package p01;
import java.io.File; import java.nio.file.Files; import java.nio.file.Paths;
public class Main {
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); } }}
In Eclipse, in the root of my project, there is a file called 'the_comedy_of_errors' (no extension) - created with File> New > File , where I pasted some content from here: http://shakespeare.mit.edu/comedy_errors/comedy_errors.1.1.html
참고URL : https://stackoverflow.com/questions/11468221/get-random-boolean-in-java
'IT TIP' 카테고리의 다른 글
| 백 슬래시 인 경우 마지막 문자 제거 (0) | 2020.11.29 |
|---|---|
| 배열 유형과 malloc으로 할당 된 배열의 차이점 (0) | 2020.11.29 |
| C #이 const 변수를 해당 값으로 바꾸는 것을 중지하는 방법은 무엇입니까? (0) | 2020.11.29 |
| org.eclipse.jetty : jetty-maven-plugin으로 서버 포트를 설정하는 방법은 무엇입니까? (0) | 2020.11.29 |
| 지도를 가질 수있는 좋은 방법이 있습니까? (0) | 2020.11.29 |