1-element Array to scalar in Julia

2019-05-19 04:39发布

Multiplying a row and a column vector, I was expecting the result to be scalar, but it is a 1-dimensional, 1-element Array:

julia> [1 2 3] * [4; 5; 6]
1-element Array{Int64,1}:
 32

Question 1: What is the rationale behind this?

Question 2: Accepting this as a quirk of Julia, I want to convert the 1-element Array into a scalar. Taking the first element with [1] is an option, but not very readable. What is the idiosyncratic way to do this?

1条回答
三岁会撩人
2楼-- · 2019-05-19 05:17

Every expression could be acted on, so you can use

([1 2 3] * [4; 5; 6])[1]

to get the first (and only value out).

There are major performance reasons for this: type-stability. Basically, in a compiled language you cannot change your types around without doing a bunch of conversions. Julia is a bit smarter, though if you do a bunch of conversions, then your code will be slower since the compiler will have to keep around a lot of "kruft" just in case you have the wrong type. Thus by ensuring type-stability, the compiler can know in advance what the type will be, and do a lot more optimizations. This is one of the performance tips. Indeed, Julia is fast and reaches C speeds BECAUSE of multiple dispatch and type-stability, and so it should be respected.

Array * Array gives out an array. In order for that to be type-stable, it must always give out an array. Otherwise the compiler needs to put extra code to check if that variable is an array or not... at every place where the output is used! So then you should use * with arrays to get arrays out. If you want to get a scalar out, the easy answer is use the dot function:

dot([1;2;3],[4;5;6])

Of course I could've just said that, but it's good to know the "why" since type-stability is such an important idea for performant code.

查看更多
登录 后发表回答