C++ 在两个浮点数之间生成随机浮点数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5289613/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:50:47  来源:igfitidea点击:

Generate random float between two floats

c++random

提问by Maks

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:

我知道如何生成 0 到 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.

回答by Wim

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 aplus something, where somethingis between 0 and b-awhich makes the end result lie in between aand b.

这通过返回aplus 的东西来工作,其中一些东西介于 0 之间,b-a这使得最终结果介于a和之间b

回答by Doug T.

float RandomFloat(float min, float max)
{
    // this  function assumes max > min, you may want 
    // more robust error checking for a non-debug build
    assert(max > min); 
    float random = ((float) rand()) / (float) RAND_MAX;

    // generate (in your case) a float between 0 and (4.5-.78)
    // then add .78, giving you a float between .78 and 4.5
    float range = max - min;  
    return (random*range) + min;
}

回答by Benjamin

Random between 2 float :

2个浮动之间的随机数:

float    random_between_two_int(float min, float max)    
{    
    return (min + 1) + (((float) rand()) / (float) RAND_MAX) * (max - (min + 1));    
}

Random between 2 int :

2 int 之间的随机数:

int    random_between_two_int(float min, float max)    
{    
    return rand() % (max - min) + min + 1;     
}

回答by Dr. Debasish Jana

Suppose, you have MIN_RAND and MAX_RAND defining the ranges, then you can have the following:

假设你有 MIN_RAND 和 MAX_RAND 定义范围,那么你可以有以下内容:

const float MIN_RAND = 2.0, MAX_RAND = 6.0;
const float range = MAX_RAND - MIN_RAND;
float random = range * ((((float) rand()) / (float) RAND_MAX)) + MIN_RAND ;

This will provide you the number scaled to your preferred range. MIN_RAND, MAX_RAND can be any value, like say 2.5, 6.6 So, the function could be as:

这将为您提供缩放到您首选范围的数字。MIN_RAND, MAX_RAND 可以是任何值,比如 2.5, 6.6 所以,函数可以是:

float RandomFloat(float min, float max) {
    return  (max - min) * ((((float) rand()) / (float) RAND_MAX)) + min ;
}