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.811 37.9260 38.66450 38.062 38.2870 53.480   100
#>     r 24.857 25.3025 26.30919 25.598 26.8055 39.263   100