One of my professors in university told us to write a random generator. He said that this is the function : x[i] = (a*x[i-1] + c) Mod m and if your system is 64 bits number m is (2^63) - 1.
He wrote this pseudo code: (MWC algorithm)
a = 65539; x[0] = 65539; m = (2^63) -1;
x[i] = ax[i-1];
if x[i] < 0
then x[i] = x[i] + m;
else R[i] = x[i] /m;
end if
And I tried to implement it in c#. Here is code I have written :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Random_Generator
{
class Program
{
static void Main(string[] args)
{
float a = 65539;
float[] x = new float[100];
x[0] = 65539;
float m = (float) Math.Pow(2,63) - 1;
for(int i = 1; i < 100; i++)
{
x[i] = (a ) * x[i - 1];
if (x[i] < 0)
x[i] = x[i ] + m;
Console.WriteLine("Random Number {0} is {1}", i, (float)(x[i]/m));
}
}
}
}
As He said it should generate m random unique numbers. But when I run this code only the first 62 numbers generate correctly. After that all of the numbers that are generated are infinite.
I really can't find the problem and I really need it.
Can any one please help me? Thanks in advance.
Aucun commentaire:
Enregistrer un commentaire