Skip to content

Commit

Permalink
Improve the performance of vec4.random by 45% (see https://jsperf.a…
Browse files Browse the repository at this point in the history
  • Loading branch information
Lakuna authored and toji committed Jul 24, 2023
1 parent bc1bbf4 commit 2534c9d
Showing 1 changed file with 11 additions and 10 deletions.
21 changes: 11 additions & 10 deletions src/vec4.js
Original file line number Diff line number Diff line change
Expand Up @@ -448,16 +448,17 @@ export function random(out, scale) {
// http://projecteuclid.org/euclid.aoms/1177692644;
var v1, v2, v3, v4;
var s1, s2;
do {
v1 = glMatrix.RANDOM() * 2 - 1;
v2 = glMatrix.RANDOM() * 2 - 1;
s1 = v1 * v1 + v2 * v2;
} while (s1 >= 1);
do {
v3 = glMatrix.RANDOM() * 2 - 1;
v4 = glMatrix.RANDOM() * 2 - 1;
s2 = v3 * v3 + v4 * v4;
} while (s2 >= 1);
var rand;

rand = glMatrix.RANDOM();
v1 = rand * 2 - 1;
v2 = (4 * glMatrix.RANDOM() - 2) * Math.sqrt(rand * -rand + rand);
s1 = v1 * v1 + v2 * v2;

rand = glMatrix.RANDOM();
v3 = rand * 2 - 1;
v4 = (4 * glMatrix.RANDOM() - 2) * Math.sqrt(rand * -rand + rand);
s2 = v3 * v3 + v4 * v4;

var d = Math.sqrt((1 - s1) / s2);
out[0] = scale * v1;
Expand Down

0 comments on commit 2534c9d

Please sign in to comment.