Reputation: 1
I have an angle say 60deg and want to generate random angle within interval say [-120,120] where the interval centred around the 60deg which be now [-60,180]
I have this code below:
http://www.cs.princeton.edu/introcs/22library/StdRandom.java.html
I'm confused because it's say that the gaussian distribution is within [0,1].
How could I pass the range [-120,120]?
The 60 angle is the relative rotation of an object the generated random angle is a predication of it's next postion
When testing the code I have angles ,say 65 ,55 if i use this angle directly it performs stranges so I take the difference 65-60 ,55-60.
Is this idea correct?
Upvotes: 0
Views: 3890
Reputation: 3703
Try this:
import java.lang.Math;
public static void main(String[] args)
{
System.out.println((int)(Math.random()*(-240))+120);
}
You have C# and Java marked as tags. Kind of confusing to figure out which one you want.
I prefer this over the Random class in java.utils because you don't have to instantiate a class. Everything you need is in the static methods of the Math class.
Breakdown:
return Math.random(); // returns a double value [0, 1]
return Math.random()*-240; // returns a double value from [-240, 0]
return (int)(Math.random()*-240); // returns an integer value from [-240, 0]
return (int)(Math.random()*-240) + 120; // returns an integer value from [-120, 120]
Upvotes: 0
Reputation: 13600
If you have a random number with a range 0 to 1, you can convert it to -120 to 120 by using:
rand_num*240 - 120
More generally, transforming any number within range [A,B] to range [C,D] involves:
num * (D-C)/(B-A) + C
I'm not sure what you mean by keeping your mean, however.
If you want a range that extends 120 in each direction, from 60, you could either do the above and add 60, or use a range [60-120,60+120]
= [-60,180]
In that sense, you'd have
rand_num * 240 - 60
following from the formula given above
Upvotes: 7
Reputation: 8531
static void Main(string[] args)
{
Random rand = new Random();
double a = 0;
for (int i = 0; i < 1000; i++)
{
double r = rand.NextDouble() * 240 - 60;
a += r;
Console.WriteLine(string.Format("ang:{0,6:0.0} avg:{1,5:0.0}", r, a / (i + 1)));
}
Console.ReadKey();
}
Upvotes: 2
Reputation: 206786
If you have something that generates random numbers in a range such as [0, 1] it's easy to transform that to another range, such as [-120, 120]: you just have to multiply by the size of the target range (240 in this case) and add the start of the target range (-120 in this case).
So, for example:
java.util.Random random = new java.util.Random();
// Generate a random number in the range [-120, 120]
double value = random.nextDouble() * 240.0 - 120.0;
Is there a special reason why you are using that StdRandom
class? Does the distribution of the random numbers have to be Gaussian? (That doesn't matter, the above will still work).
If it has to be centered around 60, then just add 60.
Upvotes: 0