what does numpy.vectorize(lambda x:1 – x^3) do?

Question:

I’m new to python and also to numpy package. I was wondering what does this specific line really do.

a = numpy.vectorize(lambda x:1 - x^3)

I’ve searched about vectorize function but didn’t really get what it does.

I’m familiar with julia if there is any instance in julia that does what this line does I could understand it faster and better.

Asked By: Eldoar

||

Answers:

The keyword lambda on Python is used to declare an anonymous function. So the statement

a = lambda x: 1 - x**3

Is mathematically equivalent to:

a(x) = 1 - x^3

The vectorize function on NumPy is used to apply a function element-wise in an array. So, suppose you have an array x with elements [1,2,3], the result of a on x is:

[1-1^3,1-2^3,1-3^3]

I am not an expert in Julia, but I believe that the equivalent would be this:

a = function(x)
        1 - x^3
    end

And then, if you want to it use the same way Python would after the vectorize function, you would add a "." after the function name:

a.([1,2,3])
Answered By: Ícaro Lorran

The closest Julia equivalent would be this:

julia> a = Base.Broadcast.BroadcastFunction(x -> 1 - x^3)
Base.Broadcast.BroadcastFunction(var"#1#2"())

julia> a([1,2,3])
3-element Vector{Int64}:
   0
  -7
 -26

Although you rarely construct BroadcastFunctions directly, as it’s usually easier to use broadcasting syntax instead.

Answered By: phipsgabler

To add to the other answer – in Julia you use just dot operator to vectorize code so when applying a lambda to all elements of a vector one would do:

julia> (x -> 1 - x^3).([1,2,3])
3-element Vector{Int64}:
   0
  -7
 -26

In the code above the dot symbol . makes the lambda to be applied to every element of the vector.

Answered By: Przemyslaw Szufel
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.