How to generate random number to express the probability - java

I don't know how to make it in JAVA.
Sorry everybody. My case is with 51% probability, I have to do something. and, with 49% probability, I don't have to do anything.
I think I need to generate a random number, which will reference, express the probability.
how can I make it suitable to my case in Java? Thank you in advanced!

You can use the Random class. It has methods such as Random.nextInt where you can give it an upper bound and it will give you a random number between 0 (inclusive) and that number (exclusive). There are also other methods like Random.nextBoolean which returns 50% chance of true or false.

You can use Math.random function alternatively. The tutorial is here
Quoting javadoc.
Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0. Returned values are chosen pseudorandomly with (approximately) uniform distribution from that range.

If you want to generate integer then you can use nextInt() method like this -
Random randomGenerator = new Random();
for (int i = 1; i <= 10; ++i){
int randomInt = randomGenerator.nextInt(100);
System.out.println("Generated : " + randomInt);
}
If you want double you can use nextDouble() method -
Random randomGenerator = new Random();
for (int i = 1; i <= 10; ++i){
int randomInt = randomGenerator.nextDouble(100);
System.out.println("Generated : " + randomInt);
}
And if you want to generate random between a range then you can do -
int shift=0;
int range=6;
Random ran = new Random();
int x = ran.nextInt(range) + shift;
This code will generate random number (int) upto 6 (from 0 to 5). If you want to generate random number shifting the lower limit then you can change the shif value. For example changing the shift to 2 will give you all random number greater than or equal 2.

Related

how would I produce 2 random integers, and then compare them?

I want to produce 2 different random integers using java.util.random. then want to compare those two numbers, for example the code produces 5 and 9. then if one number is bigger than the other, use conditional operators to put the bigger number into variable var1. end result "9 is the bigger number". this is all I have starting out.
Random rand = new Random();
int n = rand.nextInt(50);
n += 1;
System.out.println(n);
do I have to create n1 and n2 or can I produce 2 random numbers from the same variable?
Not sure why do you even want to do this that way, but you can do it like this:
Random rand = new Random();
int var1 = Math.max(rand.nextInt(50), rand.nextInt(50));
System.out.println(var1 + " is the bigger number");

Problems Generating A Math.random Number, Either 0 or 1

I want a random number, either 0 or 1 and then that will be returned to main() as in my code below.
import java.util.Scanner;
public class Exercise8Lab7 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numFlips = 0;
int heads = 0;
int tails = 0;
String answer;
System.out.print("Please Enter The Number Of Coin Tosses You Want: ");
numFlips = input.nextInt();
for(int x = 1;x <= numFlips; x++){
if(coinToss() == 1){
answer = "Tails";
tails++;
}
else{
answer = "Heads";
heads++;
}
System.out.print("\nCoin Toss " + x + ": " + answer);
}
System.out.println("\n\n====== Overall Results ======" +
"\nPercentage Of Heads: " + (heads/numFlips)*100 + "\nPercentage Of Tails: " + (tails/numFlips)*100);
}
public static int coinToss(){
double rAsFloat = 1 * (2 + Math.random( ) );
int r = (int)rAsFloat;
return r;
}
}
Many solutions had been suggested to use the util.Random option which I have done and works perfectly but I want to sort out why I can't get this to work. Obviously I want the number to be an int myself so I convert it to an int after the random number has been generated. But no matter what I add or multiply the Math.random() by, it will always all either be Heads or all either be Tails. Never mixed.
Try this) It will generate number 0 or 1
Math.round( Math.random() ) ;
You could use boolean values of 0 or 1 based on value of Math.random() as a double between 0.0 and 1.0 and make the random generator much simpler. And you can get rid completely of the coinToss() method.
if(Math.random() < 0.5) {
answer = "Tails";
tails++;
}
Remove the coin toss method and replace the first conditional with the code above.
Math.random(); by itself will return a value between 0.0 and less than 1.0. If the value is in the lower half, [0.0, 0.5), then it has the same probability of being in the upper half, [0.5, 1.0). Therefore you can set any value in the lower half as true and upper as false.
Wierd that no one is using a modulo division for the random number.
This is the simplest implementation you can get:
Random rand = new Random();
int randomValue = rand.nextInt() % 2;
Math.round(Math.random()) will return either 0.0 and 1.0. Since both these values are well within the limits of int range they can be casted to int.
public static int coinToss(){
return (int)Math.round(Math.random());
}
(int)(Math.random()*2) also works fine in this case
its not working because of the integer math you are using, the call to 2+ Math.Random is pretty much always giving you a answer between 0.0 and 1.0.
so assuming that you recieve 0.25 as your result your maths is as follows
double d = 1* (2 + 0.25); // (result = 2
Then you are checking to see if your result == 1 ( which it never will. )
A better result would be to declare java.util.Random as a class variable and call random.nextBoolean() and simply perform your heads/tails calculation on that.
If you were to continue to use Math.random() and lets say
return Math.random() < 0.5
Your results would be ever so slightly skewed due to the fact that Math.random() cannot return 1.0, due to the fact that the java API specification states:
"Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0."
Math.random() returns a random float in the range [0.0,1.0)--that means the result can be anything from 0 up to but not including 1.0.
Your code
double rAsFloat = 1 * (2 + Math.random( ) );
will take this number in the [0.0,1.0) range; adding 2 to it gives you a number in the [2.0,3.0) range; multiplying it by 1 does nothing useful; then, when you truncate it to an integer, the result is always 2.
To get integers from this kind of random function, you need to figure out how many different integers you could return, then multiply your random number by that. If you want a "0 or 1" answer, your range is 2 different integers, so multiply Math.random() by 2:
double rAsFloat = 2 * Math.random();
This gives you a random number in the range [0.0,2.0), which can then be 0 or 1 when you truncate to an integer with (int). If, instead, you wanted something that returns 1 or 2, for example, you'd just add 1 to it:
double rAsFloat = 1 + 2 * Math.random();
I think you've already figured out that the Random class gives you what you want a lot more easily. I've decided to explain all this anyway, because someday you might work on a legacy system in some old language where you really do need to work with a [0.0,1.0) random value. (OK, maybe that's not too likely any more, but who knows.)
The problem can be translated to boolean generation as follow :
public static byte get0Or1 {
Random random = new Random();
boolean res= random.nextBoolean();
if(res)return 1;
else return 0;
}
Here it the easiest way I found without using java.util.Random.
Blockquote
Scanner input = new Scanner (System.in);
System.out.println("Please enter 0 for heads or 1 for tails");
int integer = input.nextInt();
input.close();
int random = (int) (Math.random() + 0.5);
if (random == integer) {
System.out.println("correct");
}
else {
System.out.println("incorrect");
}
System.out.println(random);
This will take a random double from (0 to .99) and add .5 to make it (.5 to 1.49). It will also cast it to an int, which will make it (0 to 1). The last line is for testing.
for(int i=0;i<100;i++){
System.out.println(((int)(i*Math.random())%2));
}
use mod it will help you!
One more variant
rand.nextInt(2);
As it described in docs it will return random int value between 0 (inclusive) and the specified value (exclusive)

Generating a random number within a range. Without Overlflow. In Java

Please do not dismiss this as a duplicate of:
How to generate random positive and negative numbers in java
I need to use a Random number generator with a seed. So, I used the java.util.Random class with a constructor that takes a seed.
Random random = new Random(System.currentTimeMillis());
Then I used the solution given in the above thread
int randomValue = random.nextInt(max - min + 1) + min;
However, the problem with the above solution is that if min is a large negative number and max is a large positive number , then (max - min + 1) would result in overflow.
There should be a better solution out there. Can anyone please point me to it.
Thank you!
How about using BigInteger to avoid int overflow. Also you can use
new BigInteger(int numBits, Random rnd)
to create some BigInteger with randomized bits (up to bit specified with numBits).
So just calculate how many bits you need (range.bitLength() may be useful) check if randomized value is in specified range, so if value is greater than range random again, if everything is OK return randomized value increased by min.
Here is some code example
public static int myRandom(int min, int max, Random r){
if (max <= min)
throw new RuntimeException("max value must be greater than min value: max="+max +", min="+min);
BigInteger maxB = BigInteger.valueOf(max);
BigInteger minB = BigInteger.valueOf(min);
BigInteger range = maxB.subtract(minB);
do{
BigInteger result = new BigInteger(range.bitLength(), r);
if (result.compareTo(range)<=0)
return result.add(minB).intValueExact();
}while(true);
}

Random number in Java where one number has higher odds

I understand that in Java I can generate a random number with the following code:
Random rand=new Random()
int x=rand.nextInt(1);
I am interested generating either the number zero or one. But I want that number one has 90% higher probability of of being generated than zero.
How can I achieve that?
thanks
EDIT:
Thanks everyone. It's working.
Generate a random number from 0 to 9. If the number is 0, you return zero. If the number is 1-9, you return one.
Heres a pretty compact way to express it
Random rand=new Random();
int x = ((rand.nextInt(10) == 0)) ? 0 : 1;
This would do it:
int result;
if (Math.random() < 0.9) {
result = 1;
}
else {
result = 0;
}
Or more concise:
int result = (Math.random() < 0.9) ? 1 : 0;
read nextInt(int) manual which says:
Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence. The general contract of nextInt is that one int value in the specified range is pseudorandomly generated and returned. All n possible int values are produced with (approximately) equal probability. The method nextInt(int n) is implemented by class Random as if by:
change your code to
Random rand=new Random();
int x=rand.nextInt(10);
return (x == 0) ? 0 : 1;
then run it again
You can write it like this.
int x = (int) (Math.random() / 0.9); // 90% chance of 0
or
int x = (int) (Math.random() + 0.9); // 90% chance of 1

How to get a random between 1 - 100 from randDouble in Java?

Okay, I'm still fairly new to Java. We've been given an assisgnment to create a game where you have to guess a random integer that the computer had generated. The problem is that our lecturer is insisting that we use:
double randNumber = Math.random();
And then translate that into an random integer that accepts 1 - 100 inclusive. I'm a bit at a loss. What I have so far is this:
//Create random number 0 - 99
double randNumber = Math.random();
d = randNumber * 100;
//Type cast double to int
int randomInt = (int)d;
However, the random the lingering problem of the random double is that 0 is a possibility while 100 is not. I want to alter that so that 0 is not a possible answer and 100 is. Help?
or
Random r = new Random();
int randomInt = r.nextInt(100) + 1;
You're almost there. Just add 1 to the result:
int randomInt = (int)d + 1;
This will "shift" your range to 1 - 100 instead of 0 - 99.
The ThreadLocalRandom class provides the int nextInt(int origin, int bound) method to get a random integer in a range:
// Returns a random int between 1 (inclusive) & 101 (exclusive)
int randomInt = ThreadLocalRandom.current().nextInt(1, 101)
ThreadLocalRandom is one of several ways to generate random numbers in Java, including the older Math.random() method and java.util.Random class. The advantage of ThreadLocalRandom is that it is specifically designed be used within a single thread, avoiding the additional thread synchronization costs imposed by the other implementations. Therefore, it is usually the best built-in random implementation to use outside of a security-sensitive context.
When applicable, use of ThreadLocalRandom rather than shared Random objects in concurrent programs will typically encounter much less overhead and contention.
Here is a clean and working way to do it, with range checks! Enjoy.
public double randDouble(double bound1, double bound2) {
//make sure bound2> bound1
double min = Math.min(bound1, bound2);
double max = Math.max(bound1, bound2);
//math.random gives random number from 0 to 1
return min + (Math.random() * (max - min));
}
//Later just call:
randDouble(1,100)
//example result:
//56.736451234
I will write
int number = 1 + (int) (Math.random() * 100);
double random = Math.random();
double x = random*100;
int y = (int)x + 1; //Add 1 to change the range to 1 - 100 instead of 0 - 99
System.out.println("Random Number :");
System.out.println(y);

Categories