1 /* 2 * Copyright (c) 2006-2018, RT-Thread Development Team 3 * 4 * SPDX-License-Identifier: Apache-2.0 5 * 6 * Change Logs: 7 * Date Author Notes 8 */ 9 #include <stdlib.h> 10 #include <stdint.h> 11 #include <sys/types.h> 12 13 static unsigned int _seed=1; 14 15 /* Knuth's TAOCP section 3.6 */ 16 #define M ((1U<<31) -1) 17 #define A 48271 18 #define Q 44488 // M/A 19 #define R 3399 // M%A; R < Q !!! 20 21 int rand_r(unsigned int* seed) 22 { int32_t X; 23 24 X = *seed; 25 X = A*(X%Q) - R * (int32_t) (X/Q); 26 if (X < 0) 27 X += M; 28 29 *seed = X; 30 return X; 31 } 32 33 int rand(void) { 34 return rand_r(&_seed); 35 } 36 37 void srand(unsigned int i) 38 { 39 _seed=i; 40 } 41 42 int random(void) __attribute__((alias("rand"))); 43 void srandom(unsigned int i) __attribute__((alias("srand"))); 44