使用arc4random随机化float



我有一个浮点数,我试图得到1.5 - 2之间的随机数。我在网上看过教程,但他们都是做0到一个数字的随机化,而不是1.5在我的情况下。我知道这是可能的,但我一直在为如何真正做到这一点而挠头。有人能帮我吗?

Edit1:我在网上找到了以下方法,但我不想要所有这些小数位置。我只想要5.2或7.4之类的东西……

我如何调整这个方法来做到这一点?

-(float)randomFloatBetween:(float)num1 andLargerFloat:(float)num2
{
    int startVal = num1*10000;
    int endVal = num2*10000; 
    int randomValue = startVal + (arc4random() % (endVal - startVal));
    float a = randomValue;
    return (a / 10000.0);
}

Edit2:现在我的方法是这样的:

-(float)randomFloatBetween:(float)num1 andLargerFloat:(float)num2
{
    float range = num2 - num1;
    float val = ((float)arc4random() / ARC4RANDOM_MAX) * range + num1;
    return val;
}

这会产生像1.624566这样的数字吗?因为我只想说1.5 1.6 1.7 1.8 1.9和2.0

您可以生成一个从0到0.5的随机浮点数,并添加1.5。

编辑:

你在正确的轨道上。我会用可能的最大随机值作为除数以便得到可能值之间的最小间隔,而不是像这样任意除以10000。因此,将arc4random()的最大值定义为宏(我刚刚在网上找到了这个宏):
#define ARC4RANDOM_MAX      0x100000000

然后得到1.5到2.0之间的值:

float range = num2 - num1;
float val = ((float)arc4random() / ARC4RANDOM_MAX) * range + num1;
return val;

如果你想要,这也会给你双精度(只需将float替换为double)

编辑:

是的,这当然会给你一个小数以上的值。如果您只想要一个,只需生成一个从15到20的随机整数,然后除以10。或者你可以去掉后面多余的地方:

float range = num2 - num1;
float val = ((float)arc4random() / ARC4RANDOM_MAX) * range + num1;
int val1 = val * 10;
float val2= (float)val1 / 10.0f;
return val2;

arc4random为32位生成器。生成Uint32, arc4random()的最大值为UINT_MAX。(不要使用ULONG_MAX!)

最简单的方法是:

// Generates a random float between 0 and 1
inline float randFloat()
{
  return (float)arc4random() / UINT_MAX ;
}
// Generates a random float between imin and imax
inline float randFloat( float imin, float imax )
{
  return imin + (imax-imin)*randFloat() ;
}
// between low and (high-1)
inline float randInt( int low, int high )
{
  return low + arc4random() % (high-low) ; // Do not talk to me
  // about "modulo bias" unless you're writing a casino generator
  // or if the "range" between high and low is around 1 million.
}

这应该可以为您工作:

float mon_rand() {
  const u_int32_t r = arc4random();
  const double Min = 1.5;
  if (0 != r) {
    const double rUInt32Max = 1.0 / UINT32_MAX;
    const double dr = (double)r;
    /* 0...1 */
    const double nr = dr * rUInt32Max;
    /* 0...0.5 */
    const double h = nr * 0.5;
    const double result = Min + h;
    return (float)result;
  }
  else {
    return (float)Min;
  }
}

这是我能想到的最简单的方法,当我遇到同样的"问题"时,它对我有效:

// For values from 0.0 to 1.0
float n;
n = (float)((arc4random() % 11) * 0.1);

在你的例子中,从1.5到2.0:

float n;
n = (float)((arc4random() % 6) * 0.1);
n += 15 * 0.1;

谁想要更多的数字:

如果你只想要浮动,而不是arc4random(3),如果你使用rand48(3):

会更容易
// Seed (only once)
srand48(arc4random()); // or time(NULL) as seed
double x = drand48();

drand48()erand48()函数返回非负的、双精度的、均匀分布在区间[0.0,1.0]内的浮点值。

摘自这个答案

最新更新