Calling Julia from R using JuliaCall package

Viewed 172

I am trying to see how is the performance of Julia compared with that of R for a simple function that computes the Pi value:

sim <- function(l) {
  c <- rep(0,l)
  hits <- 0
  pow2 <- function(x) { 
      x2 <- sqrt( x[1]*x[1]+x[2]*x[2] )
      return(x2) }

  for(i in 1:l){
    x = runif(2,-1,1)
    if( pow2(x) <=1 ){
      hits <- hits + 1
    }
    dens <- hits/i
    pi_partial = dens*4
    c[i] = pi_partial
  }
  return(c)
}

I saw that there is a package called JuliaCall in R and I am trying to translate the function above from R to Julia and use the following setup:

library(JuliaCall)
julia_setup()

julia_command("
function sim(l)
  c = repeat(0,l)
  hits = 0
  function pow2(x) 
      x2 = sqrt( x[1]*x[1]+x[2]*x[2] )
      return(x2)
  end
  for i in 1:l
    x = runif(2,-1,1)
    if pow2(x) <=1 
      hits <- hits + 1
    end
    dens = hits/i
    pi_partial = dens*4
    c[i] = pi_partial
  end
  return(c)
end")

invisible(julia_call("sim", size))

It seems that the problem is coming from repeat where I don't know how to use this function in Julia. Besides that, Julia doesn't seem to complain about the rest of my translation but I don't know if it can recognize runif and arrays. Actually, I am starting with Julia. Any comment is welcome.

1 Answers

Basically the syntax of Julia is somewhat similar to Matlab and Python but very different from GnuR

The equivalent of rep is fill:

julia> fill(2,3)
3-element Vector{Int64}:
 2
 2
 2

Generating data from a uniform distribution can be done as:

julia> using Distributions

julia> rand(Uniform(-1,1),5)
5-element Vector{Float64}:
  0.7100000816870411
  0.9304865953213382
  0.6221437354059836
  0.49893080097871634
 -0.2629550300440968

And in your code you use <- for assignment which in Julia is always just = (or .= for vectorized assignments, in Julia contrary to R you need to explicitly say that you vectorize by adding a dot "." to any operator or function or by using @. macro).

Related