Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
243 views
in Technique[技术] by (71.8m points)

Java: Generating a random double between the range of a negative double and a positive double

I am not very familiar with how to alter the range of both Math.random or a new Random() to generate a double like this. I need to be able to generate a double between -10 and 25 cents (my program is dealing with money; hence why I said cents). And a separate instance is generating a random double between 90 and -75 cents. I saw this when I was searching for my answer:

double result = Math.random() * (upper - lower) + lower;

But when I implemented the idea into my code, the range didn't seem to work when using a range between a positive and a negative number... I tested it with the upper limit of 0.25 and lower of -0.10, but noticed it printed 0.3567587946356543 at one instance of the test I did. So by this I concluded that I obviously didn't adjust the range correctly..

Please help :(

This is my first time using stackoverflow so please go easy on me, I will elaborate if anything I said didn't make sense..

This is my existing method using this code:

public double variation(double price){
    //formula: (Math.random() * range) + min; where range = max - min
    //80% of the time returns amount between -10 & 25 cents
    if(Math.random() > 0.19){ 
        return (Math.random() * 0.35) - 0.10;
    }
    //20% of the time returns amount between -75 & 90 cents
    return (Math.random() * 1.65) - 0.75;
}

I know the method takes in a double price that it doesn't use; it's part of the teacher's requirements to take in a double price but to disregard its value. So ignore that please.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Now you have included all your code in the question, so my answer is changed to:

When it printed 0.3567587946356543 then it comes from the 20% part with range -.75 to 0.90 when the first Math.random() call in if(Math.random() > 0.19){ becomes false.

Old answer:

I think you forgot the minus at the lower value:

double upper = 0.25;
double lower = -0.10;
double result = Math.random() * (upper - lower) + lower;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...