Skip to content

Instantly share code, notes, and snippets.

@cho45

cho45/Math.js

Last active Jun 28, 2019
Embed
What would you like to do?
<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

This comment has been minimized.

Copy link
Owner Author

@cho45 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
You can’t perform that action at this time.