I'm looking for an algorithm to calculate ln(1-x). x is often small (<0.01), but occasionally it might be larger. Algorithm needs to be accurate, and not too slow. I'd rather not use library for ln(x), because I might lose accuracy.
Asked
Active
Viewed 3,309 times
4
-
What is the magnitude of error that is acceptable? And how large can `x` be? – Muhammad Alkarouri Sep 23 '10 at 09:12
-
Accuracy is very important, it's the reason I don't want to use a library because by log(1.0-x) I immediately lose accuracy. But the algorithm should not be orders of magnitude slower than using log(1.0-x). Finally, in some cases x might be close to 1.0, but I could of course handle those in a separate algorithm. – willem Sep 23 '10 at 09:18
-
There are specialised functions for that in many libraries, see my edited answer. – Muhammad Alkarouri Sep 23 '10 at 09:42
-
For cases where `x` is arbitrary close to 1.0 you are looking at the general `log` function, as the result becomes `-1/log(1/(1-x))` which is arbitrarily large. – Muhammad Alkarouri Sep 23 '10 at 09:45
2 Answers
3
Depending on the accuracy you want, -x
is a good approximation to small ln(1-x)
. From here.
Edit: If the reason for needing the algorithm is getting the best accuracy, then there are many libraries that are specialised for log(1+x)
. For example, in Python use log1p. Ditto in C and C++.

Muhammad Alkarouri
- 23,884
- 19
- 66
- 101
-
The links you provide do not include an algorithm. I found one using log1p as a search term: http://golang.org/src/pkg/math/log1p.go does, but is has float precision – willem Sep 24 '10 at 07:26
-
They don't include an algorithm, but every programming language I know of can use a C library in one way or another. Also, the example you found has `float64` precision, which is IEEE double precision. Can you please tell us what is your acceptable error and why you don't want to use available libraries? According to your need, somebody here may be able to help. – Muhammad Alkarouri Sep 24 '10 at 07:48
-
Aah, I understand that float64 is similar/equal to double. Then the algorithm will probably suffice. My allowable error would be a relative error of about 10^{-9}. – willem Oct 08 '10 at 07:57
0
If you are using MATLAB the log1p() function was designed specifically for calculating ln(1+x) for small values of x.

Lopez
- 1
-
1There is nothing in the question that says they are using MATLAB, so your answer is not useful. – Tony Sep 27 '14 at 22:41