# How to have random number every node run

Im using this rand() function on my code. When I first run the node, it gives me random number, but when I run the node again, it gives me the previous random number. I applied this code on turtlesim/Spawn client.

here's the snippet of the code:

    srv.request.x = rand() % 12;

srv.request.y = rand() % 12;

srv.request.theta = rand() % 360;


What happen is when I run the node, it spawns a turtle at random place but when I try to run it again, it spawns to the previous place. I also tried to use for loop to spawn 5 turtles in one run. The 5 turtles spawned at different places but when I tried to run it again, another 5 turtles are spawned onto the same place.

Is there any chance that I can have different values every time I run the node?

edit retag close merge delete

Sort by » oldest newest most voted

From https://www.cplusplus.com/reference/c..., rand():

Returns a pseudo-random integral number in the range between 0 and RAND_MAX.

This number is generated by an algorithm that returns a sequence of apparently non-related numbers each time it is called. This algorithm uses a seed to generate the series, which should be initialized to some distinctive value using function srand.

By default, a seed value of 1 is used. Hence, every time you start your program, that seed is used and you will always get the same pseudo random sequence. This can be useful for debugging, but frustrating if you're expecting something that appears random.

A common approach is to seed the random number generator with the current time, e.g.:

srand(time(0));

more

This works, Thank you so much

( 2022-04-02 11:35:54 -0500 )edit