Skip to content

Instantly share code, notes, and snippets.

@Houstonwp
Last active January 22, 2021 03:39
Show Gist options
  • Save Houstonwp/b905920baa48891117ce9523420c1ab2 to your computer and use it in GitHub Desktop.
Save Houstonwp/b905920baa48891117ce9523420c1ab2 to your computer and use it in GitHub Desktop.
library(data.table)

q <- c(0.001,
       0.002,
       0.003,
       0.003,
       0.004,
       0.004,
       0.005,
       0.007,
       0.009,
       0.011)

w <- c(0.05,
       0.07,
       0.08,
       0.10,
       0.14,
       0.20,
       0.20,
       0.20,
       0.10,
       0.04)

P <- 100
S <- 25000
r <- 0.02

dt <- as.data.table(cbind(q,w))

npv <- function(cf, r, S, P) {
  cf[, inforce := shift(cumprod(1 - q - w), fill = 1)
  ][, lapses := inforce * w
  ][, deaths := inforce * q
  ][, claims := deaths * S
  ][, premiums := inforce * P
  ][, ncf := premiums - claims
  ][, d := (1/(1+r))^(.I)
  ][, sum(ncf*d)]
}

npv(dt,r,S,P)
#> [1] 50.32483

microbenchmark::microbenchmark(npv(dt,r,S,P))
#> Unit: milliseconds
#>              expr    min      lq     mean  median      uq    max neval
#>  npv(dt, r, S, P) 2.5791 2.71035 2.964293 2.85625 3.10385 6.0357   100

Created on 2021-01-15 by the reprex package (v0.3.0)

@alecloudenback
Copy link

alecloudenback commented Jan 22, 2021

Updated Rankings for the "Life Modeling Problem":

code algorithm relative absolute timing (mean)
Julia accumulating for loop 1x 135 nanoseconds
Rust accumulating for loop 3x 360 nanoseconds
Julia vector 4x 500 nanoseconds
Python numpy vector 155x 21 microseconds
R vectorized vector 520x 70 microseconds
R data.table data.table vector 22000x 3 milliseconds

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment