C#:Random.NextDouble,包括自定义间隔的边界 [英] C#: Random.NextDouble and including borders of the custom interval

查看:155
本文介绍了C#:Random.NextDouble,包括自定义间隔的边界的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用该公式在自定义间隔中获取随机的double:

I've used that formula for gettting a random double in custom interval:

Random r = new Random();
double Upper = 3.7, Lower = 11.4, Result;    
Result = Lower + (r.NextDouble() * (Upper - Lower))
// Lower is the lower border of interval, Upper is the upper border of interval

但是请记住关于MSDN的说法NextDouble方法:

But keep in mind what MSDN says about NextDouble method:

大于或等于0.0且小于1.0的双精度浮点数.

A double-precision floating point number greater than or equal to 0.0, and less than 1.0.

这意味着我的示例代码中的时间间隔将包括3.7,但我们永远无法获得11.4,对吧?如何包含上边框?

That means interval in my sample code would include 3.7, but we can never get 11.4, right? How can I include the upper border?

Lower + (r.NextDouble() * (Upper - Lower + double.Epsilon))

这个公式能帮上忙吗?或[3.7;11.4](包括两个边界)?

Can this formula help? Or there is another variant of getting random double numbers in [3.7 ; 11.4] (including both borders) ?

推荐答案

由于您使用的精度加倍,您实际上使用哪种精度?四舍五入数字可能就足够了.另外,您也可以像这样使用自己的缩放比例:

Since your using doubles what kind of precision do you actually use? Rounding the numbers might be enough. Alternatively you can use your own scaling like this:

static void Main(string[] args)
{
    var r = new Random(3);

    for (int i = 0; i < 100; i++)
    {
        Console.WriteLine(r.NextDouble(0, 1, 100));
    }

    Console.ReadKey();
}

public static double NextDouble(this Random r
    , double lower
    , double upper
    , int scale = int.MaxValue - 1
    )
{
    var d = lower + ((r.Next(scale + 1)) * (upper - lower) / scale);
    return d;
}

这将在指定的范围内为您提供上下限范围.我使用此方法输入了比例的默认值,该默认值可为您提供最高的精度.

That will give you the lower and upper inclusive range at the specified scale. I threw in a default value for scale which gives you the highest possible precision, using this method.

这篇关于C#:Random.NextDouble,包括自定义间隔的边界的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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