Need to count sigma with x = 0.7
Thats my version of code, but it doesnt work properly, need help:
Private Sub UserForm_Click()
Dim k As Long
Dim Numerator As Double
Dim Result As Double
x = 0.7
For k = 0 To infinity Step 1
Numerator = 0
Numerator = Numerator (-1) ^ (k 1) * x ^ (2 * k - 1)
Next k
Result = Result Numerator / Application.WorksheetFunction.Fact((2 * k - 1) * (2 * k 1))
Debug.Print Result
End Sub
I get Run-time error "1004" in result line.
CodePudding user response:
Here are a few changes to your code:
- Used
n
for the number of terms in a partial sum rather thaninfinity
- It is now a function of
x
andn
rather than a sub - The unnecessary
Step 1
in the for loop has been dropped - The
2*k-1
factor has moved outside the factorial Fact
has been replaced byFactDouble
to guard against overflow- The numerators are not added together independent of the denominators. Instead, a fraction is added at each step.
Here is the code:
Function Sigma(x As Double, n As Long) As Double
Dim i As Long
Dim k As Long
Dim Numerator As Double
Dim Denominator As Double
Dim Sum As Double
For k = 0 To n
Numerator = (-1) ^ (k 1) * x ^ (2 * k - 1)
Denominator = (2 * k - 1) * Application.WorksheetFunction.FactDouble(2 * k 1)
Sum = Sum Numerator / Denominator
Next k
Sigma = Sum
End Function
For example
Sub test()
Debug.Print Sigma(0.7, 20)
End Sub
Which prints 1.65459064177857