how to make Java Rand() output between a numberset - java

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

Related

Does Java Random method return negative numbers?

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.

Random Class with seed

long seed = 0;
Random rand = new Random(seed);
int rand100 = 0;
for(int i = 0; i < 100; i++)
rand100 = rand.nextInt();
System.out.println(rand100);
I wrote this code to get 100th random integer value of given seed. I want to know if there is a way to get 100th random integer value of given seed without calling nextInt() 100 times.
I want to know if there is a way to get 100-th random integer value of given seed without calling nextInt() 100 times.
No, there is no way to directly get the 100-th random number of the sequence without first generating the other 99 values. That's simply because of how the generation works in Java, the values depend on their previous values.
If you want to go into details, take a look at the source code. The internal seed changes with every call of the next method, using the previous seed:
nextseed = (oldseed * multiplier + addend) & mask;
So in order to get the seed for the 100-th value, you need to know the seed for the 99-th value, which needs the seed for the 98-th value and so on.
However, you can easily get the 100-th value with a more compact statement like
long seed = ...
int amount = 100;
Random rnd = new Random(seed);
// Generate sequence of 100 random values, discard 99 and get the last
int val = rnd.ints(100).skip(amount - 1).findFirst().orElse(-1);
Keep in mind that this still computes all previous values, as explained. It just discards them.
After you have computed that value for the first time, you could just hardcode it into your program. Let's suppose you have tested it and it yields 123. Then, if the seed does not change, the value will always be 123. So you could just do
int val = 123;
The sequences remain the same through multiple instance of the JVM, so the value will always be valid for this seed. Don't know about release cycles though, I think it's allowed for Random to change its behavior through different versions of Java.
Yes. As long as the seed is constant, then the result of executing this 100 times will yield the same result every time. As such, you can just do
int rand100 = -1331702554;
If I got you correct, you search for some seeded method like
int[] giveMeInts(int amount, long seed);
There exists something very similar, the Stream methods of Random (documentation):
long seed = ...
int amount = 100;
Random rnd = new Random(seed);
IntStream values = rnd.ints(amount);
You could collect the stream values in collections like List<Integer> or an int[] array:
List<Integer> values = rnd.ints(amount).collect(Collectors.toList());
int[] values = rnd.ints(amount).toArray();
The methods will use the seed of the Random object, so if fed with the same seed they will always produce the same sequence of values.

Java Random.nextGaussian between 0 and 1

I'm working on an image editor and I'm about to implement filters. I decided to go with some kind of blur or noise.
Anyway, I decided I wanted a uniform filter so I read up on Random.nextGaussian().
However, since I'm working with RGB values that range from 0 to 255. How can I scale this random double value to fit within 0 and 255?
The random value returned by the nextGaussian() can range from -1 to 1 I believe.
So, I want to preserve the relative difference between the random values. "Scale" or "move the number range" if that makes sense.
I know it's possible but I can't figure it out. Thanks in advance.
Essentially, I need it to be a number between 0 and 1.
In that case you should use nextDouble().
The Gaussian distribution is a distribution that ranges over the entire collection of double values (mathematically speaking, from minus infinity to positive infinity) with a peak around zero. The Gaussian distribution is thus not uniform.
The nextDouble() method draws numbers uniformly between 0 and 1 (0 included, 1 excluded).
You can thus draw a number randomly between 0 and 255 (both inclusive) using the following code:
Random rand = new Random();
int value = (int) math.floor(256.0*rand.nextDouble());
A faster algorithm is however masking a random integer (Random.nextInt):
Random rand = new Random();
int value = rand.nextInt()&0xff;
This algorithm isn't faster in big-oh analysis, but it saves one the more expensive nextDouble method call as well as a floating point multiplication and a float-to-int conversion.
You can use nextGaussian() with Math.abs() so that you can obtain positive values of Gaussian distribution.
Random random = new Random();
double positiveRandomValue = Math.abs(random.nextGaussian());
You can fit Normal (Gaussian) distribution between ~[0,1] with adjusting mean and std. For example, use mean = 0.5, std = 0.15, and you will get value between [0,1] with total probability of 99.91%. In the end, you can ensure that value is strictly between [0,1].
Supplier<Double> alphaSupplier = new Supplier<Double>() {
#Override
public Double get() {
double value = new Random().nextGaussian() * 0.15 + 0.5;
return Math.max(0, Math.min(1, value));
}
};
double random value = alphaSupplier.get();

Differences in random functions

I am creating a random number from 1-100, I was looking at some Stackoverflow questions to look for the proper way and I got confused by the many different suggestions.
What is the difference between using this:
int random= (int)(Math.random()*((100-1)+1));
this:
int random= (int)(Math.random()*(100);
and this:
int random= 1+ (int)(Math.random()*((100-1)+1));
int random = (int)(Math.random()*(x);
This sets random equal to any integer between 0 and x - 1.
int random = 1 + (int)(Math.random()*(x);
Adding 1 to the overall expression simply changes it to any integer between 1 and x.
(int)(Math.random()*((100-1)+1))
is redundant and equivalent to
(int)(Math.random()*(100)
So take note that:
1 + (int)(Math.random()*(x) returns an int anywhere from 1 to x + 1
but
(int)(Math.random()*(x + 1) returns an int anywhere from 0 to x + 1.
I recommend that you use Random and nextInt(100) like so,
java.util.Random random = new java.util.Random();
// 1 to 100, the 100 is excluded so this is the correct range.
int i = 1 + random.nextInt(100);
it has the added benefit of being able to swap in a more secure random generator (e.g. SecureRandom). Also, note that you can save your "random" reference to avoid expensive (and possibly insecure) re-initialization.
The first is equivalent to the second. Both will give a random integer between 0 and 99 (inclusive, because Math.random() returns a double in the range [0, 1)). Note that (100-1)+1 is equivalent to 100.
The third, will give an integer between 1 and 100 because you are adding 1 to the result above, i.e. 1 plus a value in the range [0, 100), which results in the range [1, 101).

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