File: sincSEQ.R

package info (click to toggle)
r-cran-foreach 1.5.2-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 648 kB
  • sloc: makefile: 2
file content (36 lines) | stat: -rw-r--r-- 943 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
library(foreach)

# Define a function that creates an iterator that returns subvectors
ivector <- function(x, chunks) {
  n <- length(x)
  i <- 1

  nextEl <- function() {
    if (chunks <= 0 || n <= 0) stop('StopIteration')
    m <- ceiling(n / chunks)
    r <- seq(i, length=m)
    i <<- i + m
    n <<- n - m
    chunks <<- chunks - 1
    x[r]
  }

  obj <- list(nextElem=nextEl)
  class(obj) <- c('abstractiter', 'iter')
  obj
}

# Define the coordinate grid and figure out how to split up the work
x <- seq(-10, 10, by=0.1)
cat('Running sequentially\n')
ntasks <- 4

# Compute the value of the sinc function at each point in the grid
z <- foreach(y=ivector(x, ntasks), .combine=cbind) %do% {
  y <- rep(y, each=length(x))
  r <- sqrt(x ^ 2 + y ^ 2)
  matrix(10 * sin(r) / r, length(x))
}

# Plot the results as a perspective plot
persp(x, x, z, ylab='y', theta=30, phi=30, expand=0.5, col="lightblue")