1

I expected log1p(x) and log(x+1) to return the same result, but they are different by 2.775558e-17. Why don't these two functions return identical results? Is one more accurate than the other?

> y <- log({32/123}+1)
> y
#> [1] 0.2312408

> x <- log1p(32/123)
> x
#> [1] 0.2312408

> x==y
#> [1] FALSE

> y-x
#> [1] 2.775558e-17
> sprintf("%a", y-x)
#> [1] "0x1p-55"
Dewey Brooke
  • 407
  • 4
  • 10

2 Answers2

2

The function log1p exists to improve the numerical accuracy of the calculation of ln(1+x). See, for instance, this article that gives more explanation for why log1p is necessary. They aren't equal because log(1+x) is, under some circumstances, quite inaccurate, and log1p attempts to fix this. log1p isn't just shorthand.

richarddmorey
  • 976
  • 6
  • 19
1

This is due to the way how computers do floating point arithmetic. For checking that the value is reasonably near to the other, I recommend you use the dplyr::near() function. In this funciton you can also define by how much these values may differ (the tolerance) for you to still accept them as "equal".

freyberg
  • 367
  • 2
  • 9