Array is incorrectly printing previous value

aafield

New Member
Joined
May 12, 2018
Messages
1
Hi everyone,

I am building an array recursively and am not getting the correct value when I try to recall the previous value. I have two arrays in my code. fx is up to four 1's followed by 0's and gx is a recursive calculation based on fx and the previous gx values. When I type in gx(3) I get 78, but when I type gx(4) which in my function, I have defined to be gx(3), I get 72 instead of 76 and I don't know why.

My code is below.
Code:
Function function(x As Integer) As Double
    Dim fx(), gx() As Double
    ReDim fx(x + 1), gx(x + 1) As Double


    gx(1) = 1
    
    Dim i, j As Integer
    Dim S As Double


    For i = 1 To x + 1
        fx(i) = 1
    Next i


    If x > 3 Then
        For i = 4 To x + 1
            fx(i) = 0
        Next i
    End If
        
    For i = 1 To x
        If i <= 3 Then
            S = 0
            For j = 1 To i
                S = j * fx(j + 1) * gx(i - j + 1) + S
            Next j
            gx(i + 1) = 6 / i * S
        ElseIf i > 3 Then
            gx(i + 1) = gx(i)
        End If
    Next i
        
    function = gx(x + 1)
End Function
 

Excel Facts

What is the fastest way to copy a formula?
If A2:A50000 contain data. Enter a formula in B2. Select B2. Double-click the Fill Handle and Excel will shoot the formula down to B50000.
this may not be relevant, and you may not know this

Dim fx(), gx() As Double
ReDim fx(x + 1), gx(x + 1) As Double

defines fx and fx (x + 1) has variants

each has to be declared on their own to make them double
 
Upvote 0

Forum statistics

Threads
1,223,886
Messages
6,175,190
Members
452,616
Latest member
intern444

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top