产生在C#中的随机浮动的最佳方式 [英] Best way to generate a random float in C#

查看:352
本文介绍了产生在C#中的随机浮动的最佳方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是产生在C#中随机浮动的最好办法

What is the best way to generate a random float in C#?

更​​新:我想从float.Minvalue到float.Maxvalue随机浮点数。我使用的一些数学方法单元测试这些数字。

Update: I want random floating point numbers from float.Minvalue to float.Maxvalue. I am using these numbers in unit testing of some mathematical methods.

推荐答案

最好的办法,没有疯狂的价值观的distributed相对于上浮点数线可表示的区间(去掉统一为相对于连续数线是断然非均匀):

Best approach, no crazed values, distributed with respect to the representable intervals on the floating-point number line (removed "uniform" as with respect to a continuous number line it is decidedly non-uniform):

static float NextFloat(Random random)
{
    double mantissa = (random.NextDouble() * 2.0) - 1.0;
    double exponent = Math.Pow(2.0, random.Next(-126, 128));
    return (float)(mantissa * exponent);
}



另一种方法,这将给你一些疯狂的值(位模式的均匀分布) ,对于模糊可能有用的:

Another approach which will give you some crazed values (uniform distribution of bit patterns), potentially useful for fuzzing:

static float NextFloat(Random random)
{
    var buffer = new byte[4];
    random.NextBytes(buffer);
    return BitConverter.ToSingle(buffer,0);
}



最有用的方法:

Least useful approach:

static float NextFloat(Random random)
{
    // Not a uniform distribution w.r.t. the binary floating-point number line
    // which makes sense given that NextDouble is uniform from 0.0 to 1.0.
    // Uniform w.r.t. a continuous number line.
    //
    // The range produced by this method is 6.8e38.
    //
    // Therefore if NextDouble produces values in the range of 0.0 to 0.1
    // 10% of the time, we will only produce numbers less than 1e38 about
    // 10% of the time, which does not make sense.
    var result = (random.NextDouble()
                  * (Single.MaxValue - (double)Single.MinValue))
                  + Single.MinValue;
    return (float)result;
}



浮点数专线:的英特尔架构软件开发人员手册卷1:基本架构中的Y轴是对数(基数为2),因为连续的二进制浮点数字并不呈线性不同。

Floating point number line from: Intel Architecture Software Developer's Manual Volume 1: Basic Architecture. The Y-axis is logarithmic (base-2) because consecutive binary floating point numbers do not differ linearly.

这篇关于产生在C#中的随机浮动的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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