Estimate Pi

In this toy example we’ll calculate the mathematical constant π (pi) in parallel using Coiled Serverless Functions.

This should give a simple and approachable introduction to serverless functions, and how to run them in parallel.

Local Execution

We define and run the following function, which evaluates Pi to a few decimal places.

import random

def estimate_pi(n: int) -> float:
    total = 0
    for _ in range(n):
        x = random.random()
        y = random.random()
        if x ** 2 + y ** 2 < 1:
            total += 1
    return total / n * 4

pi = estimate_pi(100_000)
print(pi)

This works fine locally, but for fun, let’s run it in the cloud.

Cloud Execution

Our code is very similar to what we ran before, but now we decorate our estimate_pi function with the @coiled.function() decorator

import coiled           # New!
import random

@coiled.function()      # New!
def estimate_pi(n: int) -> float:
    total = 0
    for _ in range(n):
        x = random.random()
        y = random.random()
        if x ** 2 + y ** 2 < 1:
            total += 1
    return total / n * 4

pi = estimate_pi(100_000)
print(pi)

The first time estimate_pi runs it pauses while it spins up a remote machine running in the cloud. This takes about a minute. Then it runs our function on that cloud machine and brings back the answer.

This is about 10,000 times slower, but we used the cloud, and now we know how to create cloud machines.

Parallel Execution

We can leverage the cloud though by running this function many times in parallel. Let’s get a really good estimate of Pi by running this function thousands of times in parallel.

estimates = list(estimate_pi.map([10_000_000] * 1000))
pi = sum(estimates) / len(estimates)

Running this we’ll notice that Coiled will automatically start more machines to help us process this work. It should finish in a few minutes.

In the meantime we can navigate to the dashboard to see the new workers come up, do work in parallel, and then be released back into the cloud. You can normally find this address at estimate_pi.cluster.dashboard_link. Although if your Python session is locked waiting for results you can always navigate to cloud.coiled.io and find your dashboard there.