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

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

问题描述

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

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)稍微聪明一点,但是如果您进行大量转换,那么您的代码就会变慢,因为如果类型错误,编译器将不得不保留很多残酷"的东西.因此,通过确保类型稳定性,编译器可以提前知道类型将是什么,并进行更多的优化.这是性能提示之一.确实,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.

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

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