Exercise

Sum in parallel

In the first lesson, you learned how to split sum(1:100) into independent pieces. For two cores, you can do sum(1:50) + sum(51:100). Here, we'll implement this using clusterApply(). The parallel package is preloaded, as well as a cluster object cl with two workers.

Instructions

100 XP
  • Set the x argument of clusterApply() such that the first and second workers calculate the sum of numbers 1 through 50 and 51 through 100, respectively.

  • Unlist the output of clusterApply() and sum it to obtain the final result.

  • Compare total to sum(1:100) to ensure that the parallelized sum is correct.