Generate Random Number in .NET without using any Inbuilt Functions
I was wondering how the Random functions in every programming language works so I want to generate a number by myself i.e. I don't want开发者_JAVA百科 to use any inbuilt classes or functions.
For simplicity and speed, it's hard to beat the Xorshift random number generator. Whether it generates a good distribution is another question.
One example in C#: http://www.codeproject.com/KB/cs/fastrandom.aspx
Different languages and environments use different random number generators. As others have pointed out, there are lots of ways to generate pseudo-random numbers.
See C# Normal Random Number and other similar Stack Overflow questions.
If you are curious how it works you can start with Wikipedia: Random number generation and List of random number generators. The second link will give you list of few popular algorithms (like Mersenne Twister) that you can implement by yourself.
You can also decompile System.Random with .Net Reflector and compare given algorithms with what is implemented natively in .Net
Also, Art of Computer Programming by D. Knuth has a chapter on random numbers and their generation.
As someone else commented, you really want to rely on framework functionality for this. If this is for academic purposes or out of pure interest, there are a number of RNG algorithms that are easy to implement. One is the multiply-with-carry (MWC) algorithm, which can be easily implemented in C#:
public class RNG
{
// Seeds
static uint m_w = 362436069; /* must not be zero */
static uint m_z = 521288629; /* must not be zero */
public int NextRandom()
{
m_z = 36969 * (m_z & 65535) + (m_z >> 16);
m_w = 18000 * (m_w & 65535) + (m_w >> 16);
return (int)((m_z << 16) + m_w);
}
}
For details on MWC, see http://www.bobwheeler.com/statistics/Password/MarsagliaPost.txt
To Generate the Random number without using Random() method
using System;
public class GenerateRandom
{
private int max;
private int last;
static void Main(string[] args)
{
GenerateRandom rand = new GenerateRandom(10);
for (int i = 0; i < 25; i++)
{
Console.WriteLine(rand.nextInt());
}
}
// constructor that takes the max int
public GenerateRandom(int max)
{
this.max = max;
DateTime dt = DateTime.Now;//getting current DataTime
int ms = dt.Millisecond;//getting date in millisecond
last = (int) (ms % max);
}
// Note that the result can not be bigger then 32749
public int nextInt()
{
last = (last * 32719 + 3) % 32749;//this value is set as per our requirement(i.e, these is not a static value
return last % max;
}
}
精彩评论