Skip to content

Instantly share code, notes, and snippets.

@ryngonzalez
Created March 30, 2012 00: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 ryngonzalez/2245193 to your computer and use it in GitHub Desktop.
Save ryngonzalez/2245193 to your computer and use it in GitHub Desktop.
Functional Programming: simulating sine with an (approximate) infinite series…
apply = (f) ->
args = Array.prototype.slice.call(arguments, 1)
(x) ->
f.apply null, args.concat x
factorial = (n) ->
if n
factorial(n-1)*n
else
1
power = (x, n) ->
if n
power(x, n-1)*x
else
1
series = (f, x) ->
sum = 0
for n in [0..1000]
sum += (apply(f, x))(n)
return sum
e = (x) ->
series(
(x,n) ->
power(x,n)/factorial(n)
x
)
pi = 4*series((x,k) ->
power(-1,k)/(2*k+1)
1
)
sin = (x) ->
series(
(x,n) ->
power(-1, n)*power(x,2*n+1)/factorial(2*n+1)
x
)
console.log e(1)
console.log pi
console.log sin(pi)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment