Skip to content

Instantly share code, notes, and snippets.

@cho45
Last active June 28, 2019 06:07
Show Gist options
  • Save cho45/8336c40e1222fd86dc797d6507f589c0 to your computer and use it in GitHub Desktop.
Save cho45/8336c40e1222fd86dc797d6507f589c0 to your computer and use it in GitHub Desktop.
<script>
function SinCosTable(resolution) {
const table = new Float32Array(resolution);
for (let i = 0; i < resolution; i++) {
table[i] = Math.cos(i * Math.PI / 2 / resolution);
}
const pi = Math.PI;
return {
cos: function (n) {
let sign = 1;
if (n < 0) n = -n;
n /= pi;
n = n - ~~(n/2)*2;
if (n > 1) n = 2 - n;
if (n > 0.5) {
n = 1 - n;
sign = -1;
}
const i = ~~(n * 2 * resolution);
return table[i] * sign;
},
sin: function (n) {
return this.cos( n - pi / 2);
},
};
}
const sincos= SinCosTable(100000);
</script>
let a = 0;
for (let i = 0; i < 10000; i++) {
a += Math.sin(i);
a += Math.cos(i);
}
let a = 0;
for (let i = 0; i < 10000; i++) {
a += sincos.sin(i);
a += sincos.cos(i);
}
@cho45
Copy link
Author

cho45 commented Jun 28, 2019

Table size: 4 * resolution bytes (eg. 4 * 10000 = 40kB)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment