Does Java Random method return negative numbers? - java

I'd like to know that if I try to get a random integer using the following method, should it return negative value?
int value = new Random().nextInt(bound);

No, Random().nextInt(bound) only produces positive numbers from 0 to the number you have specified. If you want an negative number, you will need to multiply the random number by -1.
int number = new Random().nextInt(bound) * -1;
Random().nextInt() on the other hand can return you a negative number.

If you need mix of positive and negative you could use something like this:
int number = new Random().nextInt(bound);
if (number % 2 == 0) {
number *= -1;
}

If you use Random class from java.util package you are supposed to mention the type of numbers you expect, meanwhile setting an upperbound. Your answer will be anywhere from 0 to less than upperbound. nextInt() from Random class returns and integer value from 0 to the argument-1. Similarly we can use methods as nextDouble and nextLong(). The values returned are always positive or zero. Now if you need negative values we can randomly set a counter for negative numbers. Say, one another integer value which is randomly generated and checking it is odd/even to negate the number.
The other approach is to use Math.random() method. This method returns a number equal to or greater than 0 and less than 1. We can use typecasting for integer random values else by default we get double values.
P.S. Check the oracle documentation for better understanding of these classes and methods.

Related

Random Double in given range including [-MAX_VALUE,MAX_VALUE]

How do I implement a function getRandomDouble(min,max) which is able to handle +-Double.MAX_VALUEas parameter?
Online Research:
Most answers to this question are:
public Double getRandomDouble(double min, double max) {
return min + (max-min)*Random.nextDouble();
}
This works fine if min and max are not +-Double.MAX_VALUE. If so, max-min is out of range or infinity. Changing the parameters to BigDecimal solves this issue, but the result is always a double with 50 zeros and no decimals. This is the result of a very large number (2*MAX_VALUE) multiplied a double between [0,1] with only a view decimals.
So, I found a solution for +-MAX_VALUE like this:
public double getRandomDouble() {
while(true) {
double d = Double.longBitsToDouble(Random.nextLong());
if (d < Double.POSITIVE_INFINITY && d > Double.NEGATIVE_INFINITY)
return d;
}
}
This works fine, but does not consider other bounds.
How can I combine both approaches to get random double in a given range that's maybe +-MAX_VALUE?
If it's not working only with the max values, I think I have a solution.
Mathematically it should be the same:
You produce 2 random numbers and sum them up. Each number should be between -maxValue / 2 and +maxValue / 2. That way the sum will be a random number between -maxValue and +maxValue.
public Double getRandomDouble(double min, double max) {
double halfMin = min/2;
double halfMax = max/2;
double sum = halfMin + (halfMax-halfMin)*Random.nextDouble();
return sum + (halfMin + (halfMax-halfMin)*Random.nextDouble());
}
You can do this by drawing two double random numbers. The first one is used to decide if you want a negative value or a positive value. The second one is used for the actual value from the negative part or the positive part. The approach will be like this:
Calculate the quotient between the range from zero to upper bound and the range from zero to lower bound. This will get you the information like "40% the value is positive, 60% the value is negative". Use the first random number to check which it is.
Then when you know if it is negative or positive use the normal approach to get a random number between zero and the lower/upper bound. This value can only be between 0 and MAX_VALUE (or MIN_VALUE), so there will be no "overflow".
However, I don't know about the combined probability in this case, if it is the same random probability when drawing only one random double value. If you have a negative/positive split of about 5% and 95%, then the second random number will be hit a value inside the 5% or the 95%. Not sure if it still "random" or if it even creates unwanted bias.

Can't create a method to make visible a words letters randomly

I am trying to create a method to make some of the word's letters visible and other ones *. This is actually a simple word guessing game. I ask the user to choose whether they want to give an answer or request a letter. For example if the answer is "ball" and user decides to request a word, ball should turn into "*a**".
That is the method I have came up with:
public static void showALetter(String correctAnswer) {
int randomLetterIndex = (int) Math.random() % (correctAnswer.length());
for (int i = 0; i < correctAnswer.length(); i++) {
if (i == randomLetterIndex) {
System.out.print(correctAnswer.charAt(randomLetterIndex));
} else {
System.out.print("*");
}
}
}
It only shows the first letter of the correct answer at every single request. What should I do ?
Math.random() returns a double with a value between zero and one (technically [0.0, 1.0) written as a mathematical interval). This is not what you want, so you instead need to use the newer java.util.Random class:
Random random = new Random();
int randomLetterIndex = random.nextInt(correctAnswer.length());
The random.nextInt(int limit) method will return a value from zero (inclusive) to limit (exclusive) which is what you need here for your puproses.
If you're going to use random numbers over and over again, then create your Random instance as a static class member and have your methods refer to that, so that you only create the object once.
Math.random() returns a number from zero to one. So, your randomLetterIndex will always be zero. Use this instead.
(int) (Math.random() * correctAnswer.length())
This will give a random number between 0 and correctAnswer.length() - 1.
Math.random() returns a double higher or equal than 0 and less then 1, (int) Math.random() will always return 0.
Use
(int)(Math.random() * correctAnswer.length())
The modulo is useless here, this way you always hit inside the given string as (int) cast returns the floor value so the result will never be equal or higher than correctAnswer.length().

How to compare Fraction with int?

I use apach commons library(org.apache.commons.lang.math.Fraction).
Now I compare int and Fraction object like this:
private static final int MAX_VALID_RATIO = 3;
....
fraction.compareTo(Fraction.getFraction(MAX_VALID_RATIO, 1))
It looks not nice.
Fraction.getFraction(MAX_VALID_RATIO) has only double builder.
Can you advise nicer way?
You can just retrieve the intValue() of the Fraction and compare with your value:
Gets the fraction as an int. This returns the whole number part of the fraction.
This method will return the value of the fraction truncated of the decimals. For example, the fraction 10 / 3 will have an intValue() of 3.
boolean greater = fraction.intValue() >= MAX_VALID_RATIO
Comparing an integer to a fraction can be done best in 2 steps:
Get fraction.intValue and compare to your int. If your int is strictly greater or smaller than the fraction's intValue() you can stop here.
Otherwise get the fraction's deliminator and numerator and do: deliminator % numerator. If this results in 0, they are equal, otherwise the fraction is bigger.

how to make Java Rand() output between a numberset

So I need to output Random numbers between -50 and +50 using Java Standard Collections
These are then to be input into an ArrayList and sorted first ascending and 2nd time descending.
The Input and Sorting I Know how to do, but How can I generate random numbers between -50 and 50, considering these have to be input by a for do loop, one-by-one into an ArrayList
N.B. this question was for an exam, so even though the for-do loop (as an iterative) causes overheads I still need to follow these guidelines.
Thanks a lot
You can generate random number within a range start with 0 like this :
Random randomGenerator = new Random();
int randomInt=randomGenerator.nextInt(101); //This function generate number in range 0 to 100.
randomInt -= 50; //It will give you number between -50 to 50
If you want integers, then Random.nextInt will do it.
myRandom.nextInt(101) - 50
should produce a pseudo-rangom integer using a flat distribution in [-50, 50].
public int nextInt(int n)
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.
another way as well
to produce a random double :
Math.random()
to produce a random double less than 100 for example
Math.random()*100
you can cast the result to any numerical type yu want
you can produce a your result like this
double r = Math.random()*50
if(r % (int)(Math.random()*10 == 2){
r = r*-1;
}
something like that

My Math.random() method always return with 1 ? WHy?

There are 3 marbles randomly generated and i'll compare them if they are same,different or one is different. My code is below and my question is above... can u help me out ?
public static void marb(){
int a[],b[];
int num=0;
a=new int[3];
b=new int[3];
a[0]=1;
a[1]=2;
a[2]=3;
**num=(int)Math.random();** //num is always assigned 1
for(int x=0;x<3;x++)
{
num=(int)Math.random();
b[x]=a[num];
System.out.println(""+x+". marble:"+b[x]);
}
int x=0;
if(b[x]==b[x+1] && b[x+1]==b[x+2])
System.out.println("ALL SAME");
else if(b[x]!=b[x+1] && b[x]!=b[x+2] && b[x+1]!=b[x+2])
System.out.println("ALL DIFFERENT");
else
System.out.println("One is different");
}
Math.random() returns a double between 0 and 1. Casting to int will always truncate to 0.
If you want a random integer use the Random.nextInt(range) method.
Are you sure that (int) Math.random() always returns 1? If you told us that it always returns 0, I would believe that immediately.
Math.random() returns a double in the range [0;1). The conversion from double to int truncates the number, to it is always 0.
Create an instance of the random number generator
Random rand = new Random();
which also seeds the generator.
Then call
int myrandnum = rand.nextInt();
Subsequent calls to the nextInt method will generate a different number.
Math.random() returns a double >= 0 and < 1. If you want a random number between 0 and x, use (int)(Math.random() * x).
Because Math.random returns a value between 0 and 1 (either double or float I guess). Casting it to an int it loses the value after the decimal point and I guess casting rounds up to 1.
The correct way to use Math.Random() is to multiple it by the uppermost number that you want, then close the parenthesis and cast it to an int (if needed)
int randomNumber = (int)(Math.random()*max)
Its the placement of the parenthesis that you are off on. Math.random is a great function to use when you have an upper bounds for the range of numbers that you want. There is another stack overflow answer on getting it to work with a lower bounds as well, for a range of numbers from a min to a max.
Click here: Math.random() explained
My Math.random() method always return with 1
Well, this isn't true- in that case it always returns 0, which is used as num but what happens next:
b[x]=a[num];
you call a[0] three times as b[0], b[1] and b[2] and since you hardcoded
a[0]=1;
you'll get only that value.
In given example you can try
num=(int)(Math.random()*3);
as it simply generates random int from 0 to 2 or even use
num=(int)(Math.random()*a.length);
I'm not a Java programmer but I have some idea of it.
Math.random() will produce random numbers between 0 and 1. Casting to int means you want either 1 or 2.
Since you are getting only 1, Math.random() just happens to be producing numbers between 0.5 and 1, that's all.
I also know that if you run the program again and again, it will produce the same set of pseudorandom values (except maybe you recompile).

Categories

Resources