Skip to content

Instantly share code, notes, and snippets.

@p01
Last active November 6, 2016 16:47
Show Gist options
  • Save p01/085a5c15697bb4839961 to your computer and use it in GitHub Desktop.
Save p01/085a5c15697bb4839961 to your computer and use it in GitHub Desktop.
Find approximation of trigonometric value

Dirty trigonometry

This script takes a javascript expression in the range [0, 2 * Math.PI] and find the smaller integer approximation. This value can be used in a size-optimized productions or where the full precision is not needed.

I, Mathieu "p01" Henri, often use this kind of numbers in my tiny JS demos ranging from 64 bytes to 1024 bytes.

onchange = function(e) {
try {
var value = eval(expression.value);
var TWO_PI = Math.PI * 2;
var minError = TWO_PI;
var results = [];
for(var i=0; i < 1e4; i++) {
var error = Math.abs(value - (i % TWO_PI));
if (error < minError) {
minError = error;
results.push({i, error});
}
}
output.textContent = expression.value+'\n'+results.map(function(v) {
return ('::::::: ' + v.i).slice(-8) + ' -> ' + v.error + ' error';
}).join('\n');
} catch(err) {
output.textContent = err;
}
}
<!doctype html>
<style>
input, pre {
width: 90%;
box-sizing: content-box;
padding: .5rem;
margin: .5rem 0;
}
</style>
<input id="expression" placeholder="Expression ( in the range [0, 2 * Math.PI] ) to approximate e.g. Math.PI / 3"><pre id="output"></pre>
<script src="dirty_trigo.js"></script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment