Post Reply 
Convergents of a Continued Fraction
09-18-2024, 04:50 PM
Post: #2
RE: Convergents of a Continued Fraction
Code work even if continued fraction coefficient is 0. Very nice!

OP HP-42S code:

1 1 0 2 XEQ 00      --> 1 + 1/2 = 1.5
0 R/S                    --> 1 + 1/(2 + 1/0) = 1 + 1/inf = 1
3 R/S                    --> 1 + 1/(2 + 1/(0 + 1/3)) = 1 + 1/(2 + 3) = 1.2

Here is lua code to allow for Generalized Continued Fraction

[Image: dd4d1accb0958ba7af8ab6e9a615ee5168cb28d9]

We simply scale CF numerator to 1, then use OP simple continued fraction code.

x = b0 + a1/(b1 + a2/(b2 + a3/(b3 + ...
   = b0 + 1/(b1/a1 + (a2/a1)/(b2 + a3/(b3 + ...
   = b0 + 1/(b1/a1 + 1/(b2/(a2/a1) + a3/(a2/a1)/(b3 + ...

Code:
function dfc2f(b0)
    local k,u,v,w,w2 = 1,1,0,0
    return function(a, b)
        if not b then a, b = 1, a end
        k = a / k
        b = b / k   -- generalized CF to simple CF
        if not w2 then
            v = b; w2 = 1/b
        else
            u = b*w2 + w/v
            v = b + 1/v
            w, w2 = w2, u/v
        end
        return b0 + w2
    end
end


Lets try tan(pi/4)=1, using generalized CF form, and simple CF form (both are equivalent)

lua> CF1, CF2 = dfc2f(0), dfc2f(0)
lua> x = pi/4
lua> CF1(x,1), CF2(1/x)
0.7853981633974483      0.7853981633974483

lua> for k=1,8 do n=2*k+1; print(CF1(-x*x, n), CF2((-1)^k*n/x)) end
0.988689239934205        0.988689239934205
0.9997876809149683      0.9997876809149683
0.9999978684156949      0.9999978684156949
0.9999999865263551      0.9999999865263551
0.9999999999413254      0.9999999999413254
0.9999999999998131      0.9999999999998131
0.9999999999999997      0.9999999999999997
1.0000000000000002      1.0000000000000002
Find all posts by this user
Quote this message in a reply
Post Reply 


Messages In This Thread
RE: Convergents of a Continued Fraction - Albert Chan - 09-18-2024 04:50 PM



User(s) browsing this thread: 5 Guest(s)