PDA

View Full Version : taylor/maclaurin series



dwp82
11-15-2012, 03:26 AM
I am trying to devolop a vba syntax I can use within excel.

So far I have managed to come up with a maclaurin expansion for e^x


Function MacExp(x)
MacExp = 0
term = 1
k = 1
Do While term > 0
MacExp = MacExp + term
term = term * x / k
k = k + 1
If k > 100 Then
Exit Do
End If
Loop
End Function


However I am now trying to come up with a taylor series for cos x , with the function starting as "function fcos (x,n)" I have this so far, but its not getting the correct numbers out.

Function fcos(x, n)
fcos = 0
Term = 1
k = 1
Do While Term > 0
fcos = x * n
Term = Term * x / k
k = k + 1
If k < 5 Then
Exit Do
End If
Loop
End Function

thank you for any help.

Bob Phillips
11-15-2012, 04:12 AM
Why not just use the worksheet function?

dwp82
11-15-2012, 04:24 AM
Why not just use the worksheet function?

I would prefer to apply this formula though vba. So i can increase my knowolage in this area.

Teeroy
11-15-2012, 05:09 AM
1st pass through fcos(x, n) in the the Do Loop K= 1+1 which is <5 therefore the loop is exited every time.

Paul_Hossler
11-15-2012, 10:47 AM
Suggestions:

1. I like to use Option Explicit
2. I like to always Dim explicitly every function and variable
3. I'm not sure your algorithm is correct



Option Explicit
'http://www.haverford.edu/physics/MathAppendices/Taylor_Series.pdf
'pass # 1 2 3 4 ....
'cos(x) = (x^0) / 0! - (x^2) / 2! + (x^4) / 4! - (x^6) / 6! + ...

Function fcos(X As Double, Terms As Long) As Double
Dim N As Double, D As Double, Temp As Double
Dim i As Long


Paul

PS. Not saying the attached is perfect, but no peeking :friends:

Best way to learn is by making and fixing things yourself