使用arc4random随机化float? [英] Randomize float using arc4random?

查看:179
本文介绍了使用arc4random随机化float?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个浮点数,我试图得到一个介于1.5 - 2之间的随机数。我在网上看过教程,但是在我的情况下,所有这些都是0到数字而不是1.5的随机化。我知道这是可能的,但我一直在摸索如何实现这一目标。任何人都可以帮助我吗?

I have a float and I am trying to get a random number between 1.5 - 2. I have seen tutorials on the web but all of them are doing the randomization for 0 to a number instead of 1.5 in my case. I know it is possible but I have been scratching my head on how to actually accomplish this. Can anyone help me?

Edit1 :我在网上找到了以下方法,但我不想要所有这些小数位。我只想要5.2或7.4等等......

Edit1: I found the following method on the web but I do not want all these decimals places. I only want things like 5.2 or 7.4 etc...

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

How would I adjust this method to do that?

-(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 :好的,现在我的方法就像这个:

Edit2: Ok so now my method is like this:

-(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。

Will this produce numbers like 1.624566 etc..? Because I only want say 1.5,1.6,1.7,1.8,1.9, and 2.0.

推荐答案

你可以产生随机浮动从0到0.5并加1.5。

You can just produce a random float from 0 to 0.5 and add 1.5.

编辑:

你是在正确的轨道上。我会使用可能的最大随机值作为你的除数,以便在可能的值之间得到最小的间隔,而不是你所进行的任意除法。因此,将arc4random()的最大值定义为宏(我刚刚在网上找到):

You're on the right track. I would use the maximum random value possible as your divisor in order to get the smallest intervals you can between possible values, rather than this arbitrary division by 10,000 thing you have going on. So, define the maximum value of arc4random() as a macro (I just found this online):

#define ARC4RANDOM_MAX      0x100000000

然后得到介于1.5和2.0之间的值:

Then to get a value between 1.5 and 2.0:

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

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

This will also give you double precision if you want it (just replace float with double.)

再次编辑

是的,当然这会给你带有多个小数位的值。如果你只想要一个,只需产生一个从15到20的随机整数除以10.或者你可以随后砍掉额外的位置:

Yes, of course this will give you values with more than one decimal place. If you want only one, just produce a random integer from 15 to 20 and divide by 10. Or you could just hack off the extra places afterward:

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随机化float?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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