Java:在负双精度和正双精度范围之间生成随机双精度 [英] Java: Generating a random double between the range of a negative double and a positive double

查看:60
本文介绍了Java:在负双精度和正双精度范围之间生成随机双精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不太熟悉如何更改 Math.random 或新的 Random() 的范围以生成这样的双精度值.我需要能够在 -10 到 25 美分之间生成双倍(我的程序正在处理金钱;因此我说美分).一个单独的实例正在生成 90 到 -75 美分之间的随机双倍.我在寻找答案时看到了这个:

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;

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

但是当我将这个想法实现到我的代码中时,使用正数和负数之间的范围时,该范围似乎不起作用......我用 0.25 的上限和 -0.10 的下限对其进行了测试,但注意到它在我所做的一个测试实例中打印了 0.3567587946356543.所以由此我得出结论,我显然没有正确调整范围..

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..

请帮忙:(

这是我第一次使用 stackoverflow,所以请放轻松,如果我说的任何内容没有意义,我会详细说明..

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.

推荐答案

现在你已经在问题中包含了你的所有代码,所以我的答案改为:

当它打印 0.3567587946356543 时,当第一个 Math.random() 调用 if 时,它来自 20% 的部分,范围为 -.75 到 0.90(Math.random() > 0.19){ 变为 false.

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.

旧答案:

我想您忘记了较低值处的减号:

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;

这篇关于Java:在负双精度和正双精度范围之间生成随机双精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆