unixlogarithmdc

Compute logarithms in dc


I have seen this question for bc, but how do you do this in dc? For example, if the command were q, I would want to use it like this:

10k
5q2q/

To compute log_2(5).


Solution

  • There's no built-in command for this in dc, but you can implement any of the numerical methods for computing a logarithm as macros.

    For example, this one computes ln(x) using ln((1+y)/(1-y)) Taylor series expansion:

    # L (x -- y)
    # Natural logarithm of `x`.
    [ 1-d2+/
      d2*Sk              # Initialize multiplier
      d*Sy               # Initialize multiplier factor
      0Ss                # Initialize accumulator
      10K^Sp             # Initialize 10^k power
      [ d1r/lk*ls+lsrdss   # Update accumulator
        -lp*d*1 [s_q]s_>_  # Check precision
        lkly*sk 2+         # Update multiplier and counter
        lfx
      ]Sf
      1lfxLs
    LkLyLpLfs_s_s_s_] sL
    

    Use it like this:

    10k
    5lLx 2lLx /p
    

    It's not optimal, in particular for large numbers (x ≫ 1), but a method with a faster convergence can also be implemented this way, if needed.

    Squeezed version (somewhat faster):

    [1-d2+/d2*Skd*Sy0Ss10K^Sp[d1r/lk*ls+lsrdss-lp*d*1[s_q]s_>_lkly*sk2+lfx]Sf1lfxLsLkLyLpLfs_s_s_s_]sL