Java Random Number

Associate
Joined
18 Mar 2007
Posts
291
Hi guys,

Being really thick here...

I'm trying to generate a random number between 0.3 and 1.

I have written the following basic code, but can't work out why it's not working (It's returning numbers <=0.3)!

Code:
public class Random
{

    private double x;

    public Random()
    {
        for(int i=0; i<10; i++){
            x=getRandomNumber();
            System.out.println(x);
        }
    }
    
    public double getRandomNumber()
    {
        double a;
        a=(Math.random());
        if(a<=0.3) {
            getRandomNumber();
        }
        return a;
    }
}

Any help appreciated, cheers.
 
Change it to return getRandomNumber(); in your getRandomNumber() function and it will work. Pretty retarded method of doing it since your having to recalculate it each time times its not what you want. Though guess your not bothered about performance.
 
You had a recursive call to getRandomNumber() so unless by chance the first number that was generated by the call was > 0.3 you will always be making another call to the same method (recursive call). When you 'return' from a recursive call the return goes back to whoever called it, so in your case it was the method and not the constructor so you had a very slim chance of ever getting the correct numbers. This diagram might help explain:

diag.png


This should work, no more recursive calls:

Code:
public class Random
{

    private double x;

    public Random()
    {
        for(int i=0; i<10; i++){
            x=getRandomNumber();
            System.out.println(x);
        }
    }
    
    public double getRandomNumber()
    {
        double a;
        a = Math.random();
        while (a < 0.3 || a > 1.0) {
            a = Math.random();
        }
        return a;
    }
}
 
Last edited:
ah, thanks a lot mate, knew it was something so silly! just couldn't get my head around it. diagram was a massive help, thanks a lot for taking the time to do that.
 
This would be another way of doing it without going through the shenanigans of generating a new random number if it was out of range which wastes clock cycles. Basically generate an integer between 0 and 700, add 300 to it so the range is then 300-1000 and then divide by 1000 to get a decimal.

I also used java.util.Random rather than Math.random() because it supports more operations and Math.random() is based on it anyway. I've had to use the full namespace (rather than an import statement) because your class is called 'Random' which causes a namespace conflict with java.util.random.

Code:
public class Random
{

    private double x;
    private java.util.Random rand;

    public Random()
    {
        rand = new java.util.Random();
        for(int i=0; i<10; i++){
            x = (rand.nextInt(700)+300)/1000.0;
            System.out.println(x);
        }
    }
}
 
Back
Top Bottom