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.751 37.841 38.31658 38.011 38.2615 49.823   100
#>     r 25.427 25.913 26.76589 26.204 26.6250 37.439   100