在-x和x之间生成随机Double [英] Generate random Double between -x and x

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

问题描述


可能重复:

使用Java生成范围内的随机数





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

可能的输出:

-0.23
0.01
0.26
-0.4

如何生成(例如) -0.5 0.5

推荐答案

Math.random() - 0.5

Math.random 会生成 0 1 。如果您希望介于 -0.5 +0.5 之间,则只需 -0.5 从此结果。请参见 API文档

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

这不会做的一件事就是给你 0.5 作为 Math .random()永远不会返回 1 这篇帖子将为您提供更多详细信息和可能的解决方案。

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.

这篇关于在-x和x之间生成随机Double的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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