Evaluate logarithms in DC
I saw this question for bc, but how do you do it in DC? For example, if there was a command q
, I would like to use it like this:
10k 5q2q/
To calculate log_2(5)
.
source to share
There is no built-in command for this dc
, but you can implement any of the numeric methods for calculating the logarithm as macros.
For example, this this computes ln(x)
using ln((1+y)/(1-y))
the Taylor Series Extension:
# 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
This is not optimal, especially for large numbers (x "1), but a faster convergence method can also be implemented this way if needed.
Compressed version (slightly 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
source to share