Generate random Double between -x and x [duplicate

2019-07-28 09:57发布

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?

2条回答
该账号已被封号
2楼-- · 2019-07-28 10:08

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.

查看更多
来,给爷笑一个
3楼-- · 2019-07-28 10:24
return min + Math.random() * (max - min);
查看更多
登录 后发表回答