cchalmers / pcg-random

Haskell interface to the pcg random number generator
BSD 3-Clause "New" or "Revised" License
41 stars 6 forks source link

add `fromSeed` function #6

Closed listx closed 7 years ago

listx commented 7 years ago

System.Random.MWC has a nifty fromSeed function that converts the Seed type (analagous to our FrozenGen type) to a vector of Word32s. It would be nice if we could have something similar.

listx commented 7 years ago

On second thought, I suppose something as simple as exporting the FrozenGen constructor would be enough, as there are only 2 Word64s (unlike MWC which has, in comparison, huge state of 256 Word32s).

cchalmers commented 7 years ago

I don't want to export the constructor because not all seeds make a valid generator. Note that initFrozen does something to the numbers you give it. So if I added fromSeed I'd also need to add an unsafeToSeed. Alternatively, I think it's possible to offer an "inverse" of initFrozen but it would be (relatively) slow.

Out of curiosity, why do you want this? Note that FrozenGen is an instance of Generic and Data so you do in theory already have access. For example the Binary instance can be automatically derived.

listx commented 7 years ago

I did not realize that initFrozen behaved that way (for those following, it calls pcg32_srandom_r against the 2 Word64s).

My use case is this: I have a maze generator program and it depends (of course) on RNG state, i.e., FrozenGen. After a maze is generated, an info line describes the properties of the maze, such as grid size and the seed used to generate the maze. In the case where I use createSystemRandom (for random mazes without a user-defined seed), I'd like to display the seed info to the user as 2 Word64s; but right now that means show-ing FrozenGen which gives me the text FrozenGen on the screen followed by the 2 Word64 numbers in decimal, such as FrozenGen 111 222. Ideally I'd like to re-print the Word64s in hexadecimal notation, which means (currently) using a workaround of show-ing FrozenGen, read-ing it back as Word64, and finally printing it as hex.

I am too much of a Haskell newb to understand how to use Generic and Data to do what I want.

BTW, I am not sure what you mean by saying that not all seeds make a valid generator. Can you give an example?

cchalmers commented 7 years ago

In that case I suggest you use sysRandom to generate the two initial values (which is what createSystemRandom does internally) and display those for the seed. That way you'll also be able to recreate a maze given some seed.

I'm not exactly sure on the conditions for valid generators. I know a generator with both values 0 will always return zero. initFrozen always gives an odd number for the "sequence" part of the generator, but I don't know if that's necessary for a good generator.

listx commented 7 years ago

Ah, I did not see sysRandom before --- thanks. As this is sufficient for my needs, I am closing this ticket.