Last active
April 26, 2022 20:17
-
-
Save Mroik/5bb5f45aa65ffeb45b9896d6bde6d48f to your computer and use it in GitHub Desktop.
Taylor series to approximate a generic function
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
let fact x = | |
let rec fact_r i acc = | |
match i with | |
| 0.0 -> acc | |
| a -> fact_r (i - 1.0) (acc * i) | |
fact_r x 1.0 | |
let rec pwr bas ex = | |
match ex with | |
| 0 -> 1.0 | |
| _ -> bas * (pwr bas (ex - 1)) | |
let rec derivative f i delta = | |
let deri f delta = | |
let deri_r x = | |
(f (x + delta) - f x) / delta | |
deri_r | |
match i with | |
| 0 -> f | |
| _ -> derivative (deri f delta) (i - 1) delta | |
let tay_terms f point delta = | |
let tay_term i x = | |
(((derivative f i delta) point) / (fact i)) * (pwr (x - point) i) | |
let rec tay_term_r i = | |
seq { | |
yield tay_term i | |
yield! tay_term_r (i + 1) | |
} | |
tay_term_r 0 | |
let taylor f point i delta = | |
let terms = tay_terms f point delta | |
let rec taylor_r ind acc = | |
if ind > i then | |
acc | |
else | |
taylor_r (ind + 1) (fun b -> (acc b + (Seq.item ind terms b))) | |
taylor_r 0 (fun a -> 0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
My own implementation of the Taylor series after seeing @kspalaiologos blog post.
I'm fairly new to functional programming and my implementation is written in
F#
. It looks ugly and could be better. But for now it is good enough.