C, Random numbers within 1 second problem

  • Thread starter Thread starter gab_6666
  • Start date Start date
  • Tags Tags
    Numbers Random
Click For Summary
SUMMARY

The discussion addresses the issue of generating unique random numbers in C using the srand() and rand() functions. The primary problem arises from calling srand(time(0)) multiple times within the same second, which results in identical random values. The consensus is to call srand() only once at the beginning of the program to ensure a varied sequence of random numbers, as repeated calls within a short time frame will reset the seed to the same value.

PREREQUISITES
  • Understanding of C programming language
  • Familiarity with random number generation concepts
  • Knowledge of the srand() and rand() functions
  • Basic understanding of time functions in C
NEXT STEPS
  • Research the impact of seeding on random number generation in C
  • Explore alternative random number generation libraries in C
  • Learn about the rand_r() function for thread-safe random number generation
  • Investigate the use of chrono library for high-resolution timing in C++
USEFUL FOR

C programmers, software developers working with random number generation, and anyone looking to optimize random number algorithms in their applications.

gab_6666
Messages
8
Reaction score
0
Hi, I try to get different random numbers with srand(time(0)) then rand() but the problem is that the program do it million times within 1 second and return the same value 1 million times.

How could I obtain different values without sleeping the processor ?

Thanks
 
Technology news on Phys.org
srand() resets the starting point (the seed) of the random number generator.
If you use the same value for srand() you will always get the same sequence of random numbers. You should only call srand() once at the start of the program, and even that isn't really necesary.
Calling srand() with time is a quick trick to get a different number everytime the program is started, but obviously if you call it within the same second you get the same valalue.
 

Similar threads

  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 9 ·
Replies
9
Views
3K
Replies
19
Views
2K
Replies
11
Views
2K
Replies
22
Views
5K
  • · Replies 10 ·
Replies
10
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 1 ·
Replies
1
Views
3K
  • · Replies 1 ·
Replies
1
Views
4K
  • · Replies 10 ·
Replies
10
Views
4K