Skip to content

Instantly share code, notes, and snippets.

@nemzyx
Last active March 14, 2023 18:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nemzyx/c037902bbb137c139683c3e48b03b7be to your computer and use it in GitHub Desktop.
Save nemzyx/c037902bbb137c139683c3e48b03b7be to your computer and use it in GitHub Desktop.
Capturing math in LUTs with JavaScript
// save math functions in a table
const TAU = 2*Math.PI
const HALFPI = Math.PI / 2
const P = 10000 // precision factor, int arithmetic
const steps = 2048
const step = TAU/(steps)
const SIN_TABLE = []
for (let i=0;i<steps;i++) {
const data = Math.sin(i*step)
SIN_TABLE.push(Math.round(data*P))
}
const conversion = (steps*0.5)/Math.PI
const SIN = (n) => {
const index = ((TAU+n)%TAU)*conversion
return SIN_TABLE[Math.floor(index)]
}
const COS = (n) => {
const index = ((HALFPI+TAU+n)%TAU)*conversion
return SIN_TABLE[Math.floor(index)]
}
// Math.sin and Math.cos is a lot faster
// in most instances:
// https://jsben.ch/PpetH
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment