在负和正opengl es java之间生成随机浮点数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20345122/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Generating random float between negative and positive opengl es java
提问by gamdevNoobie
Im studying opengles. I want to know how can i generate between -1 to 1. Thats because opengl normalized device coordinates is only between -1 and 1. Some mentioned that random float is only between 0.0 and 0.9999999.
我正在学习opengles。我想知道如何生成 -1 到 1 之间的值。那是因为 opengl 标准化设备坐标仅介于 -1 和 1 之间。有人提到随机浮点数仅介于 0.0 和 0.9999999 之间。
here is my code
这是我的代码
points.addParticles(new GeoPoint(-random.nextFloat(),random.nextFloat(),random.nextFloat()),180);
Thats for x,y,z and random color.
那是 x,y,z 和随机颜色。
I just want to generate random points inside the screen with random location.
我只想在屏幕内生成随机位置的随机点。
采纳答案by Jon Skeet
Well Random.nextFloat
gives a value greater than or equal to 0, and less than 1 - i.e. a range of [0, 1). So to map that to a range of [-1, 1)
you just need to multiply by 2 and subtract 1.
WellRandom.nextFloat
给出大于或等于 0 且小于 1 的值 - 即范围 [0, 1)。因此,要将其映射到[-1, 1)
您的范围内,只需乘以 2 并减去 1。
float value = random.nextFloat() * 2 - 1;
In general, to get a value in the range [x, y)
you would use
一般来说,要获得[x, y)
您将使用的范围内的值
random.nextFloat() * (x - y) + x
回答by futura
Well you could use one more random, which would decide if you multiply by 1 or (-1)? if random >0.5 (first_random *1) else (first_random*(-1))
好吧,您可以再使用一个随机数,这将决定您是乘以 1 还是 (-1)?如果随机 >0.5 (first_random *1) else (first_random*(-1))