Created
November 22, 2017 03:23
-
-
Save timoxley/0521d3098b5f6865acadeb142a5064a3 to your computer and use it in GitHub Desktop.
Quick and dirty sine calculator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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