That's not quite the Taylor series for sin! But here's a clue ...
products = scanl (*) 1 [1..]
powers x = map (x^) [0..]
exp' x = zipWith (/) (powers x) products
*Main> sum (take 10 (exp' 1))
2.7182815255731922
Question
How to write Taylor series recursion data like this one:
fib = 0 : scanl (+) 1 fib
For example, I want promt something like this:
fac n = product[1..n]
sin' x = x : x^3/fac(3) : x^5/fac(5) : ...
sum $ take 10 (sin' (pi/6))
And get sum of 10 first elements of sine Taylor series.
La solution
That's not quite the Taylor series for sin! But here's a clue ...
products = scanl (*) 1 [1..]
powers x = map (x^) [0..]
exp' x = zipWith (/) (powers x) products
*Main> sum (take 10 (exp' 1))
2.7182815255731922
Autres conseils
A common approach is to use a list to represent just the coefficients of the power series and write another function to evaluate the power series at a particular value.
For example, the power series 1/(1-x)^2 = 1 + 2x + 3x^2 + ... would be represented by the list [1,2,3,...]
.
To evaluate it, we need a function:
eval :: [Float] -> Float -> Float
The base case is easy:
eval [] x = 0
The inductive case can be defined recursively:
eval (a:as) x = a + x*... -- left as an exercise
Of course, this eval
won't terminate on an infinite list, so you'll have make sure to only give it finite lists:
sin' = [ 1, 0, - 1 / fac 3, 0, 1 / fac 5, 0, ... ]
eval (take 10 sin') (pi/6)
Now you just have to generate the coefficients for sin'
. Note that in this case 10
refers to the highest power of x
you want to sum to, not the number of non-zero terms in the sum.