在 Julia 中标量的 1 元素数组 [英] 1-element Array to scalar in Julia

查看:18
本文介绍了在 Julia 中标量的 1 元素数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将行向量和列向量相乘,我期望结果是标量,但它是一个一维、一元素数组:

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

问题 1:这背后的基本原理是什么?

Question 1: What is the rationale behind this?

问题 2:接受这是 Julia 的一个怪癖,我想将 1 元素数组转换为标量.使用 [1] 获取第一个元素是一种选择,但可读性不强.这样做的特殊方法是什么?

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?

推荐答案

每个表达式都可以作用,所以你可以使用

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).

这有几个主要的性能原因:类型稳定性.基本上,在编译语言中,如果不进行大量转换,您就无法更改类型.Julia 更聪明一些,但如果你进行大量转换,那么你的代码会变慢,因为编译器必须保留很多kruft",以防万一你有错误的类型.因此,通过确保类型稳定性,编译器可以提前知道类型将是什么,并进行更多优化.这是性能提示之一.确实,Julia 速度很快并且达到了 C 速度,因为多重调度和类型稳定性,因此应该受到尊重.

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 给出一个数组.为了使其类型稳定,它必须始终给出一个数组.否则编译器需要添加额外的代码来检查该变量是否是一个数组......在每个使用输出的地方!因此,您应该将 * 与数组一起使用以获取数组.如果你想得到一个标量,简单的答案是使用 dot 函数:

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.

这篇关于在 Julia 中标量的 1 元素数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆