Generate a random float between 0 and 1

2019-01-04 22:56发布

I'm trying to generate a random number that's between 0 and 1. I keep reading about arc4random(), but there isn't any information about getting a float from it. How do I do this?

13条回答
看我几分像从前
2楼-- · 2019-01-04 23:36

Use this to avoid problems with upper bound of arc4random()

u_int32_t upper_bound = 1000000;

float r = arc4random_uniform(upper_bound)*1.0/upper_bound;

Note that it is applicable for MAC_10_7, IPHONE_4_3 and higher.

查看更多
放我归山
3楼-- · 2019-01-04 23:41
rand() 

by default produces a random number(float) between 0 and 1.

查看更多
三岁会撩人
4楼-- · 2019-01-04 23:44

Random value in [0, 1[ (including 0, excluding 1):

#define ARC4RANDOM_MAX      0x100000000
...
double val = ((double)arc4random() / ARC4RANDOM_MAX);

A bit more details here.

Actual range is [0, 0.999999999767169356], as upper bound is (double)0xFFFFFFFF / 0x100000000.

查看更多
Bombasti
5楼-- · 2019-01-04 23:45

This is extension for Float random number 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()) / Float(UInt32.max))
    }

    /// 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
    }
}
查看更多
啃猪蹄的小仙女
6楼-- · 2019-01-04 23:46

arc4random has a range up to 0x100000000 (4294967296)

This is another good option to generate random numbers between 0 to 1:

srand48(time(0));      // pseudo-random number initializer.
double r = drand48();
查看更多
手持菜刀,她持情操
7楼-- · 2019-01-04 23:49

This function works for negative float ranges as well:

float randomFloat(float Min, float Max){
    return ((arc4random()%RAND_MAX)/(RAND_MAX*1.0))*(Max-Min)+Min;
}
查看更多
登录 后发表回答