Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit testing algorithms that involve random numbers

I'm writting some code about fractals and random terrain generation. Specifically, I'm using the Diamond-Square algorithm as of now. For those of you who don't know, it basically obtains the average of four values, and adds a random number, every step. How wouldI go about testing the result? Should I use a known seed and calculate by hand the average plus the random value, or what? Should I, instead, calculate the result in the code, using the random numbers? Or is there another way? Also, some thought on the reverse process (a.k.a. TDD, writting tests before code) would be much appreciated).

like image 535
user1288851 Avatar asked Jan 15 '23 07:01

user1288851


2 Answers

You can use a mocking framework to mock your random number generation. This way you remove the randomness from your result and will be able to test your code with a static set of pre defined test cases.

In all cases you aren't testing the random number generation, but the calculations you are making. And if you whould have a fault you realy need to know the random numbers used to reproduce the fault.

like image 68
Peter Avatar answered Jan 17 '23 19:01

Peter


Just select a seed and a number for some iteration (aka how many times you call that PRNG before actually using the values from it), and use these same data (seed & iteration) in your main code and in the unit tests. These data could be in a config file that can be both accessed by the main code and the unit tests.

like image 25
karatedog Avatar answered Jan 17 '23 19:01

karatedog