0
$\begingroup$

Rosanswers logo

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?


Originally posted by naihart on ROS Answers with karma: 30 on 2022-04-01

Post score: 0

$\endgroup$

1 Answer 1

0
$\begingroup$

Rosanswers logo

From https://www.cplusplus.com/reference/cstdlib/rand/, 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)); 

Originally posted by shonigmann with karma: 1567 on 2022-04-01

This answer was ACCEPTED on the original site

Post score: 1


Original comments

Comment by naihart on 2022-04-02:
This works, Thank you so much

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.