Generate random Double between -x and x [duplicate]

风格不统一 提交于 2019-12-11 11:56:08

问题


Possible Duplicate:
Generating random number in a range with Java

double x = //Random number between -0.5 and 0.5

Possible Outputs:

-0.23
0.01
0.26
-0.4

How do I generate a double between the range of (example) -0.5 and 0.5?


回答1:


This should do it

Math.random() - 0.5

Math.random will generate betweeen 0 and 1. If you want between -0.5 and +0.5 then you can just -0.5 from this result. See the API docs

One thing that this will not do is ever give you 0.5 as Math.random() does never return 1. This post will give you more details and a possible solution.




回答2:


return min + Math.random() * (max - min);


来源:https://stackoverflow.com/questions/12395127/generate-random-double-between-x-and-x

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