Skip to content

Instantly share code, notes, and snippets.

@timoxley
Created November 22, 2017 03:23
Show Gist options
  • Select an option

  • Save timoxley/0521d3098b5f6865acadeb142a5064a3 to your computer and use it in GitHub Desktop.

Select an option

Save timoxley/0521d3098b5f6865acadeb142a5064a3 to your computer and use it in GitHub Desktop.
Quick and dirty sine calculator
// JS implementation of series definition:
// https://en.wikipedia.org/wiki/Sine#Series_definition
function sine (x, iterations = 100) {
let v = 0
for (let i = 0; i < iterations; i++) {
v += (Math.pow(-1, i)/factorial((2 * i) + 1)) * Math.pow(x, (2 * i) + 1)
}
return v
}
// alternative implementation
function sine2 (x, iterations = 100) {
let v = x
let sign = -1
for (let i = 3; i < iterations; i+=2) {
v += sign * (Math.pow(x, i)/factorial(i))
sign = -sign
}
return v
}
// performance killer
function factorial (x) {
if (x === 1) return x
return x * factorial(x - 1)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment