Berechnung von Zufallszahlen in C
- Notiz
#include <stdlib.h>
/* returns a uniformly-distributed integral number i,
with min <= i < top and with a number of rand() calls
that is smaller than a certain small number (like 4)
that depends on top-min and RAND_MAX. */double number( double min, double top )
{ { double step; do
{ step =( top - min )/( RAND_MAX + 1. );
min = min + rand() * step; top = min + step; }
while( min < top ); } return min; }- Notiz
#include <stdlib.h>
#include <time.h>unsigned int entropy( void )
{ return( unsigned int )( time( 0 )* time( 0 ) + time( 0 ) ); }int main( void )
{ srand( entropy() * entropy() + entropy() );
srand( ( unsigned int )rand() * entropy() ); rand(); rand(); rand(); }
Lotto mit C
main.c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/* returns a uniformly-distributed integral number i,
with min <= i < top. The number of rand() calls is
smaller than a certain small number (like 4) that
depends on top-min and RAND_MAX. */double number( double min, double top )
{ { double step; do
{ step =( top - min )/( RAND_MAX + 1. );
min = min + rand() * step; top = min + step; }
while( min < top ); } return min; }double random(){ return number( 0, 1 ); }
void choose
( int const number, int const max, void( * accept )( void *, int ), void * data )
{ /* Based on code by Ben Bacarisse posted to clc in 2014. */
/* The algorithm seems to be: The Art of Computer Programming;
Second Edition; Volume 2 / Seminumerical Algorithms;
3.4.2. Random Sampling and Shuffling;
Algorithm S (Selection sampling technique). */for( int i = 0, j = 0; j < number; i++ )
{ if( ( max - i )* random() < number - j )
{ accept( data, i ); ++j; }}}unsigned long entropy( void )
{ unsigned long const t = time( 0 );
return t * t + t / 7; }void randomize()
{ unsigned long e = entropy();
unsigned long r = rand();
srand( e * e + e ); rand(); rand(); rand();
srand( (( unsigned long )rand() + r )* e + e );
rand(); rand(); rand(); }void print( void * data, int const i ){ printf( "%d\n", i ); }
int main( void ){ randomize(); choose( 6, 49, print, 0 ); }
Protokoll
3
9
22
27
40
42