Home > database >  VBA Sigma Formula With Factorial
VBA Sigma Formula With Factorial

Time:11-16

enter image description here 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:

  1. Used n for the number of terms in a partial sum rather than infinity
  2. It is now a function of x and n rather than a sub
  3. The unnecessary Step 1 in the for loop has been dropped
  4. The 2*k-1 factor has moved outside the factorial
  5. Fact has been replaced by FactDouble to guard against overflow
  6. 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

  • Related