Sharing investing and trading ideas. Helping traders get started.
Advertisement

Tuesday, June 30, 2009

Continued Fractions and the Modified Lentz's Method

This articles explains how to evaluate continued fractions and offers VBA code for Excel implementation

Continued fractions are of the form below



Continued fractions can be used to express certain numbers, such as π. They are also used in calculating bessel functions of fractional orders. A general method to evaluate continued functions is known as the modified Lentz's method.

The algorithm is consists of the following steps adapted from Press et. al.
  1. f0=b0. If f0=0 then let f0=10-30 or an extremely small value ≈ 0.
  2. C0=f0
  3. D0=0
  4. For i=1 to a pre-determined number of iterations, e.g. 10000.
    Di=bi+aiDi-1. If Di=0, let Di=10-30 or an extremely small value ≈ 0.
    Ci=bi+ai/Ci-1. If Ci=0, let Ci=10-30 or an extremely small value ≈ 0.
    Di=1/Di
    Chgi=CiDi
    fi=fi-1Chgi
  5. Exit when |Chgi-1| is smaller than a specified threshold.
These steps assume that you should stop when the change in f(x) becomes sufficiently small. By iterating the above twice, it becomes obvious how the algorithm works
The VBA implementation of the algorithm is as follows

'Declare your variables
Dim anow As Double, bnow As Double
Dim achange As Double, bchange As Double
Dim Cnow As Double, Dnow As Double
Dim fnow As Double, n As Long, Chgnow As Double
Dim small1 As Double, stop1 As Double
Dim answer As Range

'Set your variables
anow = 1
bnow = 2
achange = 1
bchange = 1
n = 9999
small1 = 10 ^ -30
stop1 = 10 ^ -15
Set answer = Range("B3")

'Start iterating
If bnow = 0 Then
fnow = small1
Else
fnow = bnow
End If
Cnow = fnow
Dnow = 0

For i = 1 To n
anow = anow + achange
bnow = bnow + bchange
Dnow = anow * Dnow + bnow
If Dnow = 0 Then Dnow = small1
Cnow = anow / Cnow + bnow
If Cnow = 0 Then Cnow = small1
Dnow = 1 / Dnow
Chgnow = Cnow * Dnow
fnow = fnow * Chgnow
If Abs(Chgnow - 1) <>
answer.Value = fnow
End
End If
Next i
answer.Value = fnow
End Sub

The code above is also adpated from Press et. al. However, it assumes that ai and bi will increase by 1 for each iteration.

References
Numerical Recipes The Art of Scientific Computing 3ed
William H. Press, Saul, A. Teukolsky, William T. Vetterling and Brian P. Flannery 2007
Cambridge University Press


Like what you have just read? Digg it or Tip'd it.
The objective of Finance4Traders is to help traders get started by bringing them unbiased research and ideas. Since late 2005, I have been developing trading strategies on a personal basis. Not all of these models are suitable for me, but other investors or traders might find them useful. After all, people have different investment/trading goals and habits. Thus, Finance4Traders becomes a convenient platform to disseminate my work...(Read more about Finance4Traders)

1 comments:

Unknown said...

Appreciate your posts! awriter Thank you!

Post a Comment