Created
June 17, 2015 13:22
-
-
Save allykzam/825a24bfb03c0cc2cac7 to your computer and use it in GitHub Desktop.
Sine and cosine implementation in F# using the Taylor series?
This file contains 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
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