views:

265

answers:

3

How can I make it so the same sequence of random numbers come out of an MSVC++ program and a C# .NET program?

Is it possible? Is there any relationship between MSVC++ rand() and System.Random?

Given the example below it seems they are totally different.

#include <iostream>
using namespace std;

int main()
{
  srand( 1 ) ;

  cout << rand() << endl <<
    rand() << endl <<
    rand() << endl ;
}
using System;

class Program
{
  static void Main( string[] args )
  {
    Random random = new Random( 1 );

    Console.WriteLine( random.Next() );
    Console.WriteLine( random.Next() );
    Console.WriteLine( random.Next() );
  }
}
+3  A: 

The easiest way to do this would be to make an unmanaged reference to a C++ DLL that contains the random number generator with a parameter as the seed. Then you can be sure they're the same.

Stefan Mai
+2  A: 

It is possible (not exactlly easy) to use .NET mangaged libraries in unmanaged C++. You might want to take a look at the MSDN documentation.

Lucas McCoy
+3  A: 

Yes they are very different functions. Occasionally you'll find that BCL classes are just very thin wrappers around their native counterparts using PInvoke to execute them. This is not the case with System.Random. It is a 100% managed implementation and is completely separate from the srand version.

Can you help us out a bit and explain why you want to have the same set of numbers? Is it for testing for instance?

If you do truly want to have the same set of random numbers, one option is to create a simple COM object which wraps srand. The COM object would be available to both your managed and native code and hence would be able to proffer up the same algorithm in both places.

JaredPar
I'm porting one of my own projects to C# from C++.Its a type of simulation, and i want to quickly check if I've missed anything by using the same sequence of random numbers, so I can _expect_ the sim to look identical in both windows!
bobobobo