floating point - Convert float to log space in python -
i implementing viterbi algorithm (a dynamic algorithm) in python, , notice large input files, probabilities keep getting multiplied , shrinking beyond floating point precision. need store numbers in log space.
can give simple example python code-snippet of how convert, say, 0.0000003 log-space? (i'm not sure if needs natural log or other log. have heard of "log-space" don't know it.)
thanks!
to move log space, use log
. move again use exp
. the rules in log space different - eg. perform multiplication add in logspace.
>>> math import log, exp >>> log(0.0000003) -15.01948336229021 >>> exp(-15.01948336229021) 3.0000000000000015e-07 >>> log(0.0000003) + log(0.0000003) -30.03896672458042 >>> exp(-30.03896672458042) 9.000000000000011e-14 # 0.0000003 * 0.0000003
here example using small probabilities
>>> probabilities = [0.0000003, 0.0000004, 0.0000005] >>> exp(sum(log(p) p in probabilities)) 5.999999999999992e-20
Comments
Post a Comment