Maybe something like this:

See http://docs.julialang.org/en/release-0.4/manual/parallel-computing/ 
(particularly 
section Parallel Map and Loops)

@everywhere f(x) = 4/(1+(x*x))

function calc_pi(n)
    a,b = 0,1
    dx = (b-a)/n
    sumfx = @parallel (+) for x in a:dx:b
        f(x)
    end
    return sumfx * dx
end

function test_pi()
    for e in 1:9
        n = 10^e
        pi_approx = calc_pi(n)
        @printf("%12d %20.15f %20.15f\n", n, pi_approx, pi_approx - pi)
    end
end



On Monday, July 18, 2016 at 2:50:06 PM UTC+10, Arundhyoti Sarkar wrote:

> Hi Guys,
>
> I am trying to run Julia on a cluster for the first time. Essentially I 
> want to calculate the value of Pi by numerical integration. integration of 
> 4/(1+x*x) from 0 to 1 = pi 
> I have written this piece of code but I am unable to parallelize it 
> properly. 
>
> ```
> n=1000000 # larger the value, larger the number of pieces for integration, 
> greater the precision.
> @everywhere f(x) = 4/(1+(x*x))
> a,b = 0,1
> delta = (b-a)/n
> xs = a+ (0:n-1) * delta
> pieces = pmap(f,xs)
> r1 = @spawn cpi_P.calsum(pieces[1:5])
> r2 = @spawn cpi_P.calsum(pieces[6:end])
>
> println("Process 1 : ",fetch(r1)* delta)
> println("Process 2 : ",fetch(r2)* delta)
> print("PI = ")
> ```
> cpi_P.jl is a module containing the following
> ```
> module cpi_P
> export calsum
>
>   function calsum(fx)
>         sum = 0
>         for i in 1:size(fx,1)
>                sum = sum + fx[i]
>         end
>         return sum
>    end
>
> end
> ```
> The above code works when the number of processes are 2. I want to 
> generalize this to N processes where I can assign N set of pieces for 
> integration using @parallel. Problem is that calsum is dependent on the 
> limits and the cpi_P module needs to accept fx and the limits as inputs. 
>
> I am a novice. Any kind of help will e deeply appreciated. Thanks!
>
>

Reply via email to