C# 2个双数之间的随机数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1064901/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Random Number Between 2 Double Numbers
提问by CodeLikeBeaker
Is it possible to generate a random number between 2 doubles?
是否可以在 2 个双打之间生成一个随机数?
Example:
例子:
public double GetRandomeNumber(double minimum, double maximum)
{
return Random.NextDouble(minimum, maximum)
}
Then I call it with the following:
然后我用以下命令调用它:
double result = GetRandomNumber(1.23, 5.34);
Any thoughts would be appreciated.
任何想法将不胜感激。
采纳答案by Michael
Yes.
是的。
Random.NextDouble returns a double between 0 and 1. You then multiply that by the range you need to go into (difference between maximum and minimum) and then add that to the base (minimum).
Random.NextDouble 返回一个介于 0 和 1 之间的双精度值。然后将其乘以需要进入的范围(最大值和最小值之间的差值),然后将其添加到基数(最小值)中。
public double GetRandomNumber(double minimum, double maximum)
{
Random random = new Random();
return random.NextDouble() * (maximum - minimum) + minimum;
}
Real code should have random be a static member. This will save the cost of creating the random number generator, and will enable you to call GetRandomNumber very frequently. Since we are initializing a new RNG with every call, if you call quick enough that the system time doesn't change between calls the RNG will get seeded with the exact same timestamp, and generate the same stream of random numbers.
真正的代码应该有 random 是一个静态成员。这将节省创建随机数生成器的成本,并使您能够非常频繁地调用 GetRandomNumber。由于我们在每次调用时都初始化一个新的 RNG,如果调用速度足够快,系统时间在调用之间不会改变,RNG 将获得完全相同的时间戳,并生成相同的随机数流。
回答by Greg D
The simplest approach would simply generate a random number between 0 and the difference of the two numbers. Then add the smaller of the two numbers to the result.
最简单的方法是简单地生成一个介于 0 和两个数字之差之间的随机数。然后将两个数字中较小的一个添加到结果中。
回答by Malcolm
You could use code like this:
你可以使用这样的代码:
public double getRandomNumber(double minimum, double maximum) {
return minimum + randomizer.nextDouble() * (maximum - minimum);
}
回答by user490775
You could do this:
你可以这样做:
public class RandomNumbers : Random
{
public RandomNumbers(int seed) : base(seed) { }
public double NextDouble(double minimum, double maximum)
{
return base.NextDouble() * (maximum - minimum) + minimum;
}
}
回答by Ajibola
About generating the same random number if you call it in a loop a nifty solution is to declare the new Random() object outside of the loop as a global variable.
关于在循环中调用它时生成相同的随机数,一个不错的解决方案是将循环外的新 Random() 对象声明为全局变量。
Notice that you have to declare your instance of the Random class outside of the GetRandomInt function if you are going to be running this in a loop.
请注意,如果要在循环中运行它,则必须在 GetRandomInt 函数之外声明 Random 类的实例。
“Why is this?” you ask.
“为什么是这样?” 你问。
Well, the Random class actually generates pseudo random numbers, with the “seed” for the randomizer being the system time. If your loop is sufficiently fast, the system clock time will not appear different to the randomizer and each new instance of the Random class would start off with the same seed and give you the same pseudo random number.
嗯,Random 类实际上生成伪随机数,随机数的“种子”是系统时间。如果您的循环足够快,系统时钟时间将不会与随机生成器不同,并且 Random 类的每个新实例都将从相同的种子开始,并为您提供相同的伪随机数。
Source is here : http://www.whypad.com/posts/csharp-get-a-random-number-between-x-and-y/412/
来源在这里:http: //www.whypad.com/posts/csharp-get-a-random-number-between-x-and-y/412/
回答by Mark Byers
Johnny5 suggested creating an extension method. Here's a more complete code example showing how you could do this:
Johnny5 建议创建一个扩展方法。这是一个更完整的代码示例,展示了如何执行此操作:
public static class RandomExtensions
{
public static double NextDouble(
this Random random,
double minValue,
double maxValue)
{
return random.NextDouble() * (maxValue - minValue) + minValue;
}
}
Now you can call it as if it were a method on the Random
class:
现在你可以像调用Random
类的方法一样调用它:
Random random = new Random();
double value = random.NextDouble(1.23, 5.34);
Note that you should not create lots of new Random
objects in a loop because this will make it likely that you get the same value many times in a row. If you need lots of random numbers then create one instance of Random
and re-use it.
请注意,您不应Random
在循环中创建大量新对象,因为这可能会使您连续多次获得相同的值。如果您需要大量随机数,则创建一个实例Random
并重新使用它。
回答by Chris Susie
What if one of the values is negative? Wouldn't a better idea be:
如果其中一个值为负怎么办?不是更好的主意是:
double NextDouble(double min, double max)
{
if (min >= max)
throw new ArgumentOutOfRangeException();
return random.NextDouble() * (Math.Abs(max-min)) + min;
}
回答by Mitesh Savani
Random random = new Random();
double NextDouble(double minimum, double maximum)
{
return random.NextDouble()*random.Next(minimum,maximum);
}
回答by Leniel Maccaferri
Watch out: if you're generating the random
inside a loop like for example for(int i = 0; i < 10; i++)
, do not put the new Random()
declaration inside the loop.
注意:如果您在random
循环内部生成例如for(int i = 0; i < 10; i++)
,请不要将new Random()
声明放在循环内。
From MSDN:
从MSDN:
The random number generation starts from a seed value. If the same seed is used repeatedly, the same series of numbers is generated. One way to produce different sequences is to make the seed value time-dependent, thereby producing a different series with each new instance of Random. By default, the parameterless constructor of the Random class uses the system clock to generate its seed value...
随机数生成从种子值开始。如果重复使用相同的种子,则会生成相同的一系列数字。产生不同序列的一种方法是使种子值与时间相关,从而为每个新的 Random 实例产生不同的序列。默认情况下,Random 类的无参数构造函数使用系统时钟来生成其种子值...
So based on this fact, do something as:
所以基于这个事实,做一些事情:
var random = new Random();
for(int d = 0; d < 7; d++)
{
// Actual BOE
boes.Add(new LogBOEViewModel()
{
LogDate = criteriaDate,
BOEActual = GetRandomDouble(random, 100, 1000),
BOEForecast = GetRandomDouble(random, 100, 1000)
});
}
double GetRandomDouble(Random random, double min, double max)
{
return min + (random.NextDouble() * (max - min));
}
Doing this way you have the guarantee you'll get different double values.
这样做你可以保证你会得到不同的双精度值。
回答by alex
If you need a random number in the range [double.MinValue
; double.MaxValue
]
如果您需要范围内的随机数 [ double.MinValue
; double.MaxValue
]
// Because of:
double.MaxValue - double.MinValue == double.PositiveInfinity
// This will be equals to NaN or PositiveInfinity
random.NextDouble() * (double.MaxValue - double.MinValue)
Use instead:
改用:
public static class RandomExtensions
{
public static double NextDoubleInMinMaxRange(this Random random)
{
var bytes = new byte[sizeof(double)];
var value = default(double);
while (true)
{
random.NextBytes(bytes);
value = BitConverter.ToDouble(bytes, 0);
if (!double.IsNaN(value) && !double.IsInfinity(value))
return value;
}
}
}