Julia: How to convert numeric string with power symbol "^" into floating point number

时间:2019-03-19 15:04:03

标签: julia

I'm having trouble converting an array of numeric strings into an array of corresponding floating point numbers. A (hypothetical) string array is:

arr = ["8264.", "7.1050^-7", "9970.", "2.1090^-6", "5.2378^-7"]

I would like to convert it into:

arr = [8264., 1.0940859076672388e-6, 9970., 0.011364243260505457, 9.246079446497013e-6]

As a novice of Julia, I have no clue on how to make power operator "^" in the string format to do the correct job in the conversion. I highly appreciate your suggestions!

2 个答案:

答案 0 :(得分:4)

此函数将解析两种形式,而没有指数。

{{1}}

答案 1 :(得分:2)

Somewhat ugly, but gets the job done:

eval.(Meta.parse.(arr))

UPDATE:

Let me elaborate a bit what this does and why it's maybe not good style.

Meta.parse converts a String into a Julia Expression. The dot indicates that we want to broadcast Meta.parse to every string in arr, that is apply it to every element. Afterwards, we use eval - again broadcasted - to evalute the expressions.

This produces the correct result as it literally takes every string as a Julia "command" and hence knows that ^ indicates a power. However, besides being slow, this is potentially insecure as one could inject arbitrary Julia code.

UPDATE:

A safer and faster way to obtain the desired result is to define a short function that does the conversion:

julia> function mystr2float(s)
           !occursin('^', s) && return parse(Float64, s)
           x = parse.(Float64, split(s, '^'))
           return x[1]^x[2]
       end
mystr2float (generic function with 1 method)

julia> mystr2float.(arr)
5-element Array{Float64,1}:
 8264.0
    1.0940859076672388e-6
 9970.0
    0.011364243260505457
    9.246079446497013e-6

julia> using BenchmarkTools

julia> @btime eval.(Meta.parse.($arr));
  651.000 μs (173 allocations: 9.27 KiB)

julia> @btime mystr2float.($arr);
  5.567 μs (18 allocations: 1.02 KiB)

UPDATE:

Performance comparison with @dberge's suggestion below:

julia> @btime mystr2float.($arr);
  5.516 μs (18 allocations: 1.02 KiB)

julia> @btime foo.($arr);
  5.767 μs (24 allocations: 1.47 KiB)