Skip to contents

Calculate sum(x^2), but faster when the number of elements exceeds 1000.

Arguments

x

double, integer, or logical vector/matrix

Value

A numerical scalar

Examples


x <- rnorm(10000)
sumsquared(x)
#> [1] 9876.546

# Compare speed
microbenchmark::microbenchmark(
  cpp = {sumsquared(x)},
  r = {sum(x^2)}
)
#> Unit: microseconds
#>  expr    min      lq     mean median     uq    max neval
#>   cpp 37.831 37.9555 38.64399 38.056 38.336 50.805   100
#>     r 23.434 24.0250 24.79977 24.406 24.866 34.254   100