在两个浮点之间生成随机浮点数 [英] Generate random float between two floats
本文介绍了在两个浮点之间生成随机浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道这是一个很简单的问题,但我只是不太好的数学。
我知道如何生成一个随机浮点数0和1 :
float random =((float)rand())/(float)RAND_MAX;
- 但是,如果我想要一个函数,浮动,在该范围内返回伪随机浮点数。
示例:
< $ p>
RandomFloat(0.78,4.5); //可能返回2.4124,0.99和4.1等
解决方案
float RandomFloat(float a,float b){
float random =((float)rand())/(float)RAND_MAX;
float diff = b - a;
float r = random * diff;
return a + r;
}
这可以通过返回 a
加上某事,其中 在0和 ba
之间, $ c> a 和 b
。
I know this is a rather simple question, but I'm just not too good at maths.
I know how to generate a random float between 0 and 1:
float random = ((float) rand()) / (float) RAND_MAX;
- But what, if I want a function that given a range of two floats, returns a pseudorandom float in that range?
Example:
RandomFloat( 0.78, 4.5 ); //Could return 2.4124, 0.99, 4.1, etc.
解决方案
float RandomFloat(float a, float b) {
float random = ((float) rand()) / (float) RAND_MAX;
float diff = b - a;
float r = random * diff;
return a + r;
}
This works by returning a
plus something, where something is between 0 and b-a
which makes the end result lie in between a
and b
.
这篇关于在两个浮点之间生成随机浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文