00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022 #include <inttypes.h>
00023 #include <limits.h>
00024 #include <math.h>
00025 #include "lfg.h"
00026 #include "md5.h"
00027 #include "intreadwrite.h"
00028 #include "attributes.h"
00029
00030 void av_cold av_lfg_init(AVLFG *c, unsigned int seed)
00031 {
00032 uint8_t tmp[16] = { 0 };
00033 int i;
00034
00035 for (i = 8; i < 64; i += 4) {
00036 AV_WL32(tmp, seed);
00037 tmp[4] = i;
00038 av_md5_sum(tmp, tmp, 16);
00039 c->state[i ] = AV_RL32(tmp);
00040 c->state[i + 1] = AV_RL32(tmp + 4);
00041 c->state[i + 2] = AV_RL32(tmp + 8);
00042 c->state[i + 3] = AV_RL32(tmp + 12);
00043 }
00044 c->index = 0;
00045 }
00046
00047 void av_bmg_get(AVLFG *lfg, double out[2])
00048 {
00049 double x1, x2, w;
00050
00051 do {
00052 x1 = 2.0 / UINT_MAX * av_lfg_get(lfg) - 1.0;
00053 x2 = 2.0 / UINT_MAX * av_lfg_get(lfg) - 1.0;
00054 w = x1 * x1 + x2 * x2;
00055 } while (w >= 1.0);
00056
00057 w = sqrt((-2.0 * log(w)) / w);
00058 out[0] = x1 * w;
00059 out[1] = x2 * w;
00060 }
00061
00062 #ifdef TEST
00063 #include "log.h"
00064 #include "timer.h"
00065
00066 int main(void)
00067 {
00068 int x = 0;
00069 int i, j;
00070 AVLFG state;
00071
00072 av_lfg_init(&state, 0xdeadbeef);
00073 for (j = 0; j < 10000; j++) {
00074 START_TIMER
00075 for (i = 0; i < 624; i++) {
00076
00077 x += av_lfg_get(&state);
00078 }
00079 STOP_TIMER("624 calls of av_lfg_get");
00080 }
00081 av_log(NULL, AV_LOG_ERROR, "final value:%X\n", x);
00082
00083
00084 {
00085 double mean = 1000;
00086 double stddev = 53;
00087
00088 av_lfg_init(&state, 42);
00089
00090 for (i = 0; i < 1000; i += 2) {
00091 double bmg_out[2];
00092 av_bmg_get(&state, bmg_out);
00093 av_log(NULL, AV_LOG_INFO,
00094 "%f\n%f\n",
00095 bmg_out[0] * stddev + mean,
00096 bmg_out[1] * stddev + mean);
00097 }
00098 }
00099
00100 return 0;
00101 }
00102 #endif