Question

I have to port a c++ program to C#.

Random numbers are involved in the program. I have to produce exactly same random numbers in both program to get same results in testing.

In C++ I use

srand(1000)
...
double r = (double)rand() / (double)(RAND_MAX);

and in C# I use

private readonly Random _rnd = new Random(1000);
...
_rnd.NextDouble()

However programs produces different numbers despite same seed. Is there any way to produce same random numbers?

Was it helpful?

Solution 2

Essentially both random functions (srand vs Random) have different underlying implementations, thus you can't rely on them giving the same output. So why not provide a set of "n" numbers and feed them into your algorithm in both c++ and c# - just for testing purposes ofcourse? This way you're always certain you'll have the same amount, the same numbers and the same order.

e.g.: a file with on every line some numbers, then read it out in both c++/c# and then feed those numbers into the algorithm you're trying to "test".

(Also, what is it that you want to test here? An algorithm you wrote (the ported algorithm thus), or the "random" capabilities in both languages? Because, depending on your answer to my questions above, the answer that would be relevant to your case might differ a lot! So could you provide us with some more context?)

OTHER TIPS

Do you know, what algorithm is used for c++ rand and c# Random class?

You can try to implement some PNG on your own. Eg. LCG algorithm is very simple and easily implementable in both languages...Just use some common parameters from the wiki page.

i used this

Random rnd = new Random();

as my declaration.

and this:

Convert.ToString(rnd.Next(1, 49))

as the execution when the button is pressed.

maybe you can have a useful use of this.

Greetings

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top