如何生成0(包括)和1(不包括)之间的随机浮点数

时间:2013-10-02 13:12:14

标签: objective-c

使用(float)arc4random()如何生成包含在[0,1]中的浮点随机数[即在0-1区间,包含0且排除1?

我的代码是

  do { 
          c = ((float)arc4random() / 0x100000000);
     }
  while (c == 1.0);

有什么更好的吗?

4 个答案:

答案 0 :(得分:3)

这取决于你想要的两个可能的数字?

但你可以使用......

float numberOfPossibilities = ...;
float random = (float)arc4random_uniform(numberOfPossibilities) / numberOfPossibilities;

要排除1你可以做...

float random = (float)arc4random_uniform(numberOfPossibilities - 1) / numberOfPossibilities;

答案 1 :(得分:2)

// Get a value greater than the greatest possible random choice
double one_over_max = UINT32_MAX + 1L;
// Use that as the denominator; this ratio will always be less than 1
double half_open_result = arc4random() / one_over_max;

分辨率 - 可能的结果值的数量 - 因此与原始随机函数的分辨率相同。最大结果与间隔顶部之间的差距是您所选分母与原始结果数之间的差异,而不是分母。在这种情况下,那是1/4294967296;非常小。

答案 2 :(得分:0)

这是Float Swift 3.1

的扩展名
// MARK: Float Extension

public extension Float {

    /// Returns a random floating point number between 0.0 and 1.0, inclusive.
    public static var random: Float {
        return Float(arc4random()) / 0xFFFFFFFF
    }

    /// Random float between 0 and n-1.
    ///
    /// - Parameter n:  Interval max
    /// - Returns:      Returns a random float point number between 0 and n max
    public static func random(min: Float, max: Float) -> Float {
        return Float.random * (max - min) + min
    }
}

答案 3 :(得分:-2)

你可以使用:

Float num = (arc4random() % ([[filteredArrayofPerticularword count] FloatValue]));

在filteredArrayofPerticularword数组中,你可以存储你的号码。

相关问题