Post Reply 
Natural logarithm of 2 [HP-15C/HP-42S/Free42 & others]
11-14-2019, 05:34 PM
Post: #24
RE: Natural logarithm of 2 [HP-15C/HP-42S/Free42 & others]
Another way to speedup log(2) calculations is to use ... uh ... log(2) Big Grin

Let r = roughly the value of log(2)

log2 = r + log2 - r = r + log(2 exp(-r))

Last term should be tiny:

log(2 exp(-r)) = log(1 + ε) = 2 atanh(x)

With r = 0.6931471805599453, x = ε/(ε+2) ≈ 4.7e-18

→ atanh(x) converge very quickly, +35 decimal digits per loop.

Code:
OPTION ARITHMETIC DECIMAL_HIGH
LET nd = 1000
PRINT "Log(2) ="
LET t = TIME
LET r = 0.6931471805599453    !'log2 16 digits
LET a = r*r
LET x = 1
LET y = 0.5 - r               !'y = exp(-r) - 1/2
FOR k = 3 TO 425 STEP 2       !'k loops = 212
   LET x = x * a / (k*k-k)
   LET y = y + x * (k-r)      !'2 terms at a time
NEXT k
LET x = y / (y+1)             !'log(1+2y) = 2*atanh(x)
LET a = x*x
LET s = x
FOR d = 3 TO 57 STEP 2        !'d loops = 28
   LET x = x*a
   LET s = s + x / d
NEXT d
LET s = r + 2*s               !log2 = r + 2*atanh(x)
LET r = TIME - t

LET r$ = STR$(s)                           
PRINT
PRINT "0";
PRINT r$(0:1);
FOR i = 2 TO nd + 1
   PRINT r$(i:i);
   IF MOD((i - 1),10) = 0 THEN PRINT " ";
   IF MOD((i - 1),50) = 0 THEN 
      PRINT
      PRINT "  ";
   END IF
NEXT i
IF MOD (i - 2,50) <> 0  OR nd = 0 THEN PRINT
PRINT 
PRINT "Runtime: ";
PRINT  USING "0.##": r;
PRINT " seconds"
END
Find all posts by this user
Quote this message in a reply
Post Reply 


Messages In This Thread
RE: Natural logarithm of 2 [HP-15C/HP-42S/Free42 & others] - Albert Chan - 11-14-2019 05:34 PM



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