How adapt this sequential code to Nx?

I’ve a code in this form:

def test(0, _), do: 1
def test(n, a) do
    na = a * a
    if (na > 100) do
        test(n - 1, na)

Is there a way to use Nx numerical definitions and tensors to make it parallel in GPU?

The algorithm seems to be a serial problem. Unless you have a lot of numbers you want to test at once, Nx will not speed up the process.

You can look into NIFs to forward the calculation to another programming language. Rustler is pretty easy to use when you know Rust.

1 Like

Thanks jnnks.

But why transferring the problem to another programming language would be better than doing it in Elixir? If there is benefit I will definitely take a look at Rustler.

Elixir has a lot of benefits as a programming language, but doing fast calculations is not one of those. Here are a few reasons why:

  • Elixir is running in a virtual machine (like Java or Python) and the code you write is not executed directly. There are a lot of steps involved, before that, which slow down even simple calculations
  • There are no specialized numbers in Elixir. You can do all operations (add, subtract, etc.) on any two numbers. Your CPU can only work with the same kind of number, so they need to be converted

Here is a comparison for many programming languages regarding arithmetic: GitHub - niklas-heer/speed-comparison: A repo which compares the speed of different programming languages..

This is the Rustler I was talking about: GitHub - rusterlium/rustler: Safe Rust bridge for creating Erlang NIF functions :slight_smile:

1 Like

Ah, I understand now. Thanks a lot jnnks.