Is it possible for Math.random() to return a value greater than 1? [duplicate]

允我心安 提交于 2019-12-13 07:58:51

问题


Is it possible to return a value like 1.125155, which is a double value greater than 1?

My code:

Math.random()

回答1:


This is not possible if you are using java.lang.Math. (Read Doc)




回答2:


You can do something like this :

 Random ran = new Random();
 double x = ran.nextDouble() + 1

The x is now the random number that has double value greater than 1.




回答3:


You can move the decimal place using BigDecimal like this...

Random ran = new Random();
double result = BigDecimal.valueOf(ran.nextDouble()).movePointRight(1).doubleValue()

If you don't have to convert back to double the code will be cleaner and you'll have more control over rounding issues if you plan on using the returned value in further calculations (above I have converted back to double as this is what your OP asked for).




回答4:


Math.random() returns a double from [0,1]; Therefore, to get it to return a number great than 0 you would have to do one of a couple of things

Math.random() + 1 returns an number from [0+1, 1+1] or [1,2]

Math.random() * 2 returns a number from [0*2, 1*2] or [0,2]




回答5:


There is a workaround to it if you want to use two values which possibly should be random and never be same(random function sometimes give same value when executed twice), then put your values to a list and use list.shuffle() Hope this helps.



来源:https://stackoverflow.com/questions/42525278/is-it-possible-for-math-random-to-return-a-value-greater-than-1

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!