This page contains an archived post to the Java Answers Forum made prior to February 25, 2002.
If you wish to participate in discussions, please visit the new
Artima Forums.
Message:
Implementing Probability in Java ?
Posted by avinsinanan on February 22, 2002 at 2:16 PM
Hello, Am trying to incorporate probablity in one of my Java applications. I know how to generate random numbers. But how does one set the probablity of a random number be genrated. I know it sounds kinda funny.. becasue the whole point of it being random is that the probablity of any nimber should be the same. But I've included some code. The code does the following : It generates a random number between 0 and 10. And if the the number is less than 4 it perfroms a function. If the number is more than or equal to 4 it does a function. But how does one set the probablity of the number being generated. For eaxmple if the I wanted the probablity of 7 being genrated to be 0.4 and the probablity of a 3 being generated 0.1 and so on. Does anyone out there have any ideas? Here is the code. And thanks for reading. yours respectfully Avin import java.util.Random.*;
class AvinThread { public static void main( String argv[]) { Start1 start1 = new Start1(); Start2 start2 = new Start2(); for(int i=0 ; i<100; i++) { int number =(int)(Math.random()*10); if(number< 4) { start1.method1(); } if(number >= 4) { start2.method2(); } } } }
class Start1 extends Thread { public Start1() { } public synchronized void method1() {
System.out.println("HEY"); } } class Start2 extends Thread { public Start2() { } public synchronized void method2() { System.out.println(" WOW "); } }
Replies:
|