ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question

How to have random number every node run

asked 2022-04-01 20:16:11 -0600

naihart gravatar image

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 flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2022-04-01 20:57:30 -0600

shonigmann gravatar image

From, 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.:

edit flag offensive delete link more


This works, Thank you so much

naihart gravatar image naihart  ( 2022-04-02 11:35:54 -0600 )edit

Question Tools

1 follower


Asked: 2022-04-01 20:16:11 -0600

Seen: 224 times

Last updated: Apr 01 '22