Skip to content

Instantly share code, notes, and snippets.

@allykzam
Created June 17, 2015 13:22
Show Gist options
  • Save allykzam/825a24bfb03c0cc2cac7 to your computer and use it in GitHub Desktop.
Save allykzam/825a24bfb03c0cc2cac7 to your computer and use it in GitHub Desktop.
Sine and cosine implementation in F# using the Taylor series?
open System
let degToRad deg = deg * (Math.PI / 180.0)
// This is a very slow implementation of the sine function, and could be easily
// optimized in a lot of ways, but I wanted to know how to calculate sine, and
// this works.
// Taken from the accepted answer at:
// https://math.stackexchange.com/questions/501660/is-there-a-way-to-get-trig-functions-without-a-calculator
let sine angle places =
[1 .. places] |> List.fold (fun counter value ->
let pow = (((float value) * 2.0) + 1.0)
let numerator = angle ** pow
let denominator = [2.0 .. pow] |> List.fold ( * ) 1.0
let result = numerator / denominator
if value % 2 = 0
then counter + result
else counter - result
) angle
sine (degToRad 27.0) 4
// Just for kicks, here's a definition for cosine too. As above, this is slow,
// use Math.Sin and Math.Cos for real work, but it's interesting to write a
// working implementation.
let cosine angle places =
[1 .. places] |> List.fold (fun counter value ->
let pow = ((float value) * 2.0)
let numerator = angle ** pow
let denominator = [2.0 .. pow] |> List.fold ( * ) 1.0
let result = numerator / denominator
if value % 2 = 0
then counter + result
else counter - result
) 1.0
cosine (degToRad 27.0) 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment