Question
I am trying to code a random number generation function in embedded C where I can't include the math.h
file. Thats why I'm not able to use the seed srand
function.
Is there any other way to seed it other than time?
Solution
Consider using the Mersenne Twister, sources are e.g. here -- much higher quality than traditional linear congruential generators, superbly long period, deeply studied in, and blessed by, plenty of recent academic literature.
OTHER TIPS
srand
is instdlib.h
, notmath.h
. To seed with time you includetime.h
to usetime(NULL)
, notmath.h
. I don't see how it's relevant.- If
rand
andsrand
are not available, you can create one your own, e.g. LCG or Mersenne twister. - If speed and security is not a concern, you can store the current PRNG state in persistent memory and restart from that point when a random number is required. For instance, MT19937 has period of 219937 - 1 which should be enough for normal purpose when without reseeding.
- If seeding is really required, anything that is not constant in any scales can be used as the seed.
Consider having a looksee through this lecture, might give you some ideas (and code). The pdf goes through a few different options, and even gives a bit of code.
I am trying to code a random number generation function in embedded C where I can't include the
math.h
file. Thats why I'm not able to use the seedsrand
function.
srand()
is commonly seeded using time()
, and that is defined in <time.h>
, not in <math.h>
.
Is there any other way to seed it other than time?
Of course, you can seed it with anything you want. It depends on your platform what is available.