QB64.org Forum
Active Forums => Programs => Topic started by: jack on April 30, 2019, 07:35:40 pm
-
for amusement only :)
_TITLE "logarithm_cf"
'computing logarithms by constructing a continued fraction
' by jack
'see http://demonstrations.wolfram.com/ApproximatingTheLogarithmOfAnyBaseWithContinuedFractions/
' and http://www.numbertheory.org/pdfs/log.pdf
DIM nbase AS DOUBLE, number AS DOUBLE
DO
INPUT "log base, number ", nbase, number
IF nbase < 1E-9 OR number < 1E-9 THEN EXIT DO
PRINT lg(nbase, number)
LOOP
FUNCTION lg# (nbase AS DOUBLE, number AS DOUBLE)
DIM b AS DOUBLE, x AS DOUBLE, p0 AS DOUBLE, p1 AS DOUBLE
DIM n AS DOUBLE, n0 AS DOUBLE, n1 AS DOUBLE, d AS DOUBLE
DIM d0 AS DOUBLE, d1 AS DOUBLE, t AS DOUBLE, er AS DOUBLE
er = 1E-9
IF nbase > 1 AND number > 0 THEN
IF nbase = number THEN
lg = 1
EXIT FUNCTION
ELSEIF number = 1 THEN
lg = 0
EXIT FUNCTION
ELSE
b = nbase
x = number
IF x < b THEN
n0 = 1
n1 = 0
d0 = 0
d1 = 1
ELSE
SWAP b, x
n0 = 0
n1 = 1
d0 = 1
d1 = 0
END IF
er = er * x
WHILE (b - 1) > er
p0 = 1
IF x = b THEN
t = 2
x = 1
ELSE
t = 0
WHILE p0 < b
p1 = p0
p0 = p0 * x
t = t + 1
WEND
END IF
t = t - 1
n = t * n1 + n0: n0 = n1: n1 = n
d = t * d1 + d0: d0 = d1: d1 = d
PRINT n; "/"; d, n / d
b = b / p1
SWAP b, x
WEND
END IF
END IF
lg = n / d
END FUNCTION
-
Hi jack,
This is interesting subject for me but my attentions are on Sudoku improvements at moment.
I look at continued fractions (at Wiki for starters) and think I know how some people feel about recursive procedures, ha!
Then I wonder if this could be simplified, like explained in English to eighth grader or by rewriting the code with a single base like 10, 2 or e.
I also wonder how this might be written as a recursive procedure. A recursive procedure must require a test for stopping. I would use the difference between the last result and current. When that is less than say your "er" then time to stop.
I also wonder how this method compares to Taylor or Maclaurin Series.
-
Hi bplus :)
I will see if I can clobber up an in-a-nutshell explanation later, but to answer your question about Taylor series, Taylor series are faster and efficient.