PDA

View Full Version : VBA Macro for taylor Series of Sine (x)

Mr.Gatsby
09-14-2016, 10:03 PM
Hi,

i am trying to teach my self VBA so i can use it at work to minimize my time while computing data coming in.

i am stuck on writing the program to solve the Expansion of the Maclaurin's Series for sin (x)

This is what i have done so far;

'Dimensionalize'
Dim sum As Double
Dim x As Double
Dim Fact As Integer
Dim N As Integer

'call Values'
x = Range("B4")
N = Range("B3")
sum = 0
Fact = 1

'Math solving stuff'
For i = 1 To N
Fact = Fact * (2 * i - 1)
sum = sum + (((-1) ^ i) * ((x) ^ (2 * i - 1)) / (Fact))
Fact = Fact * 2 * i
Next

Range("b7") = sum

I am lost at what i have done wrong at this point.

lecxe
09-15-2016, 02:35 AM
Hi
Welcome to the board

Try:

'Math solving stuff'
...
For i = 1 To N
sum = sum + (-1) ^ (i + 1) * x ^ (2 * i - 1) / Fact
Fact = Fact * (2 * i) * (2 * i + 1)
Next
...

Also dimensioning Fact as Integer is a bad choice. Integer has a very low max value and you'll only be able to use 3 terms.
Even if you dimension Fact as Long you'll only be able to use 5 terms, which you may deem as enough.
For more terms, dimension Fact as Double

Dim Fact As Long ' or Double

Paul_Hossler
09-15-2016, 02:54 PM
You could also make the function into a Function

Option Explicit
Sub drv()
MsgBox Maclaurin_Sin(0.25, 2)
MsgBox Maclaurin_Sin(0.25, 4)
MsgBox Maclaurin_Sin(0.25, 8)
MsgBox Maclaurin_Sin(0.25, 16)
MsgBox Maclaurin_Sin(0.5, 2)
MsgBox Maclaurin_Sin(0.5, 4)
MsgBox Maclaurin_Sin(0.5, 8)
MsgBox Maclaurin_Sin(0.5, 16)
End Sub

Function Maclaurin_Sin(X As Double, N As Long) As Double
Dim Temp As Double, Fact As Double
Dim i As Long
Temp = 0#
Fact = 1#
For i = 1 To N
Temp = Temp + (-1) ^ (i + 1) * X ^ (2 * i - 1) / Fact
Fact = Fact * (2 * i) * (2 * i + 1)
Next
Maclaurin_Sin = Temp
End Function