Java:在范围内(包括范围内的最小值和最大值)生成随机双精度数 [英] Java: Generating a random double within a range (inclusive of the min and max to the range)

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

问题描述

我需要生成-0.10和0.25之间(包括-0.10和0.25)之间的随机双精度数.我还没有完全理解Java的随机数生成器,所以我不太确定如何做到这一点.我知道下面的代码会生成一个在该范围内的数字,但是我几乎100%确信它还没有包含在内.我如何将其更改为包括范围的最小值和最大值?

I need to generate a random double between -0.10 and 0.25 inclusive of -0.10 and 0.25. I don't completely understand random number generators with java yet so I'm not quite sure how to do this. I know that the code below generates a number within that range, but I'm almost 100% certain it's not inclusive yet. How would I change it to be inclusive of the min and max of the range?

public double randDouble() {
    //formula: (Math.random() * (max - min) + min
    //in this case, min = -0.10 and max = 0.25
    return (Math.random() * 0.35) - 0.10;
}

我的问题与@javaguy所讨论的问题不同,因为没有人在该线程的哪个地方说过如何在两端实现包容性.而且我已经测试了这段代码,但是没有看到-.10或0.25的输出,因此除非我的测试不够大,否则我看不到它如何包含两端.

My question is different than the one @javaguy is talking about because no where on that thread does someone say how to make this inclusive on both ends. And I've tested this code, but haven't seen an output of -.10 or 0.25 so unless my tests just weren't big enough, I can't see how it's inclusive of both ends.

推荐答案

由于您希望-0.10到0.25之间的值(包括两端值),我建议使用另一种方法来控制随机值的粒度.使用Math.random()将返回介于0.0(含)和1.0(不含)之间的值,因此,使用您的方法将永远不会得到0.25的值.而是使用Random()类,并使用整数使两端都包含在内.

Since you want values between -0.10 and 0.25 both inclusive, i would suggest a different approach to control the granularity of your random values. Using Math.random() will return values between 0.0(inclusive) and 1.0(exclusive), so using your approach you will never get the value of 0.25. Instead use the Random() class and use integers to get both ends inclusive.

Random randomValue = new Random();
int randomInt = randomValue.nextInt(3501) - 1000; //Will get integer values between -1000 and 2500
Double rangedValue = Double(randomInt)/10000.0 // Get values between -0.10 and 0.25 

或者,您可以通过增加传递给randomValue.nextInt()的值的大小,并相应地更改最后一行中所指定的值,来保留小数位数.

Alternatively you can more decimal places by increasing the magnitude of the values passed into randomValue.nextInt() and accordingly altering the value being devided by in the last line.

这篇关于Java:在范围内(包括范围内的最小值和最大值)生成随机双精度数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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