Skip to content

Commit d3ebc1a

Browse files
committed
Fix portability bug in get_normal_pair (RAND_MAX != MAX_RANDOM_VALUE).
Also try to improve readability and performance.
1 parent 49c8609 commit d3ebc1a

File tree

1 file changed

+15
-19
lines changed

1 file changed

+15
-19
lines changed

contrib/tablefunc/tablefunc.c

Lines changed: 15 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -224,31 +224,27 @@ get_normal_pair(float8 *x1, float8 *x2)
224224
v2,
225225
s;
226226

227-
for (;;)
227+
do
228228
{
229-
u1 = (float8) random() / (float8) RAND_MAX;
230-
u2 = (float8) random() / (float8) RAND_MAX;
229+
u1 = (float8) random() / (float8) MAX_RANDOM_VALUE;
230+
u2 = (float8) random() / (float8) MAX_RANDOM_VALUE;
231231

232232
v1 = (2.0 * u1) - 1.0;
233233
v2 = (2.0 * u2) - 1.0;
234234

235-
s = pow(v1, 2) + pow(v2, 2);
235+
s = v1 * v1 + v2 * v2;
236+
} while (s >= 1.0);
236237

237-
if (s >= 1.0)
238-
continue;
239-
240-
if (s == 0)
241-
{
242-
*x1 = 0;
243-
*x2 = 0;
244-
}
245-
else
246-
{
247-
*x1 = v1 * sqrt((-2.0 * log(s)) / s);
248-
*x2 = v2 * sqrt((-2.0 * log(s)) / s);
249-
}
250-
251-
return;
238+
if (s == 0)
239+
{
240+
*x1 = 0;
241+
*x2 = 0;
242+
}
243+
else
244+
{
245+
s = sqrt((-2.0 * log(s)) / s);
246+
*x1 = v1 * s;
247+
*x2 = v2 * s;
252248
}
253249
}
254250

0 commit comments

Comments
 (0)