juliatyped-arraysijulia-notebook

Is it possible to convert an Array{Num,1} to Array{Float64,1} in Julia?


I have the following function that uses symbolics in Julia. Everything works fine until the moment of plotting

using Distributions
using Plots
using Symbolics
using SymbolicUtils

function BinomialMeasure(iter::Int64, p::Float64, current_level = nothing)

@variables m0 m1

if current_level == nothing
    current_level = [1]
end
next_level = []
for item in current_level
    append!(next_level, m0*item)
    append!(next_level, m1*item)
end

If iter != 0
    current_level = next_level
    return BinomialMeasure(iter - 1, p , current_level)
else
    return [substitute(i, Dict([m0 => p, m1 => 1 - p])) for i in next_level]
end
end

y = BinomialMeasure(10, 0.4)
x = [( i + 1 ) / length(y) for i = 1:length(y) ]
append!(x, 0)
append!(y,0)
plot(x,y) 

Then it returns the following:

MethodError: no method matching AbstractFloat(::Num)
Closest candidates are:
AbstractFloat(::Real, !Matched::RoundingMode) where T<:AbstractFloat at rounding.jl:200
AbstractFloat(::T) where T<:Number at boot.jl:716
AbstractFloat(!Matched::Bool) at float.jl:258 

y is an Array{Num,1} and x is an Array{Float64,1}.

I tried map(float, y), convert(float,y) and float(y), but I think it not possible to convert a type Num to a Float64 or at least I don't know how to do it.


Solution

  • you can access the field val without using string and parse

    y_val = [i.val for i in y]
    

    this will of course have way better performance than parsing a string