Post Reply 
Natural logarithm of 2 [HP-15C/HP-42S/Free42 & others]
11-17-2019, 03:01 PM
Post: #27
RE: Natural logarithm of 2 [HP-15C/HP-42S/Free42 & others]
(11-15-2019 10:58 AM)toml_12953 Wrote:  It's not good practice to reuse a variable other than loop indices.
Since r is already used for the run time, you should use some variable other than r for LOG(2).

This faster version renamed variable r as g.

To speedup exp(-g): exp(-g) = exp(-g/n) ^ n, where n = 2^24

This reduce exp() loop count from 212 down to 55.

Code:
OPTION ARITHMETIC DECIMAL_HIGH
LET n = 2^24
LET nd = 1000
PRINT "Log(2) ="
LET t = TIME
LET g = 0.6931471805599453    !'log2 16 digits
LET h = g / n
LET a = h*h
LET x = 1
LET s = 1 - h                 !'s = exp(-h)
FOR k = 3 TO 111 STEP 2       !'loops = 55
   LET x = x * a / (k*k-k)
   LET s = s + x * (k-h)      !'2 terms at a time
NEXT k
LET s = s^n - 0.5             !'s = exp(-g) - 0.5
LET x = s / (s+1)             !'log(1+2s) = 2*atanh(x)
LET a = x*x
LET s = x
FOR k = 3 TO 57 STEP 2        !'loops = 28
   LET x = x*a
   LET s = s + x / k
NEXT k
LET s = g + 2*s               !log2 = g + 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-17-2019 03:01 PM



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