Home > database >  How to iterate a list or vector of numbers containing decimals in Julia?
How to iterate a list or vector of numbers containing decimals in Julia?

Time:07-31

function distribucion(x::Vector)
    for i in x
        if x[i] > 1
            return error("The values have to be between 0 and 1")
        elseif x[i] < 0
            return error("The values have to be between 0 and 1")
        end
    end 
end

x = collect(0:0.01:1) 
distribucion(x) Error:ArgumentError:invalid index:0.0 type Float64

Hi, I'm learning to use the Julia language but I've had some doubts and it's the following: how can I iterate a vector that contains decimals between 0 and 1? What happens is that I declared a function that receives a vector but when iterating and putting conditionals it shows me an error, could someone help me? Attached code of what I did along with the error that appears

I have this problem when i tried to run the code : Error:ArgumentError:invalid index:0.0 type Float64

CodePudding user response:

As already mentioned in the comment above:

function distribucion(x::Vector)
    for elem in x # iterate elements of vector
        if elem > 1 || elem < 0
            return error("The values have to be between 0 and 1, the value received was ", elem)
        end
    end
end

x =collect(0:0.01:1)
append!(x, 2.1) # test
distribucion(x)

CodePudding user response:

This code could be also written as:

function distribution(x)
    @assert all(0 .<= x .<= 1) "The values have to be between 0 and 1"
end

This works with any x (scalar, Vector, Matrix) - in Julia there is usually no need to limit the argument type. Note the dot operator (.) that vectorizes the comparison operation.

CodePudding user response:

It will be much faster if you provide a predicate to any or all functions in Julia because it avoids allocating a new array. The easiest in your case might be @assert all(i->0<=i<=1, x), but if you want a specific error message, you can use the following:

@assert all(i->0<=i<=1, x) "All values have to be between 0 and 1"

This has zero allocations and is about 4X faster than 0 .<= x .<= 1. It also works for scalars, vectors, or matrices.

  • Related