Guest User

Untitled

a guest
Dec 13th, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.75 KB | None | 0 0
  1. logsumexp <- function(l) {
  2. n <- length(l);
  3. L <- sort(l, decreasing = TRUE);
  4. S <- rep(L[1], n);
  5. for (k in 1:(n-1)) {
  6. S[k+1] <- max(L[k+1], S[k]) + log1p(exp(-abs(L[k+1] - S[k]))); }
  7. S[n]; }
  8.  
  9. #Generate large number of small log-probabilities
  10. set.seed(1);
  11. n <- 10^6;
  12. l <- rnorm(n, -3000, 1);
  13.  
  14. #Calculate logsumexp using above function and package
  15. library(matrixStats);
  16. l1 <- logsumexp(l);
  17. l2 <- matrixStats::logSumExp(l);
  18.  
  19. print(l1, digits = 20)
  20. [1] -2985.6845568559206
  21. print(l2, digits = 20)
  22. [1] -2985.6845568559038
  23.  
  24. #Test calculation speed of functions (specific to my PC - not reproducible)
  25. TIME1 <- system.time(logsumexp(l));
  26. TIME2 <- system.time(matrixStats::logSumExp(l));
  27.  
  28. TIME1[3]
  29. elapsed
  30. 0.7
  31.  
  32. TIME2[3]
  33. elapsed
  34. 0.05
Add Comment
Please, Sign In to add comment