gpt4 book ai didi

julia - 滚动阵列,均匀圆形移位

转载 作者:行者123 更新时间:2023-12-03 23:29:06 25 4
gpt4 key购买 nike

给定一个数组:
arr = [1, 2, 3, 4, 5]
我想转移所有元素。
shift!(arr, 2) => [4, 5, 1, 2, 3]
在 Python 中,这是通过 Numpy 使用 numpy.roll 完成的。 .这是如何在 Julia 中完成的?

最佳答案

无需自己实现,有内置函数

julia> circshift(arr, 2)  
5-element Array{Int64,1}:
4
5
1
2
3

它也(稍微)比 roll2 更有效上面建议:
julia> @btime circshift($arr, 2);
68.563 ns (1 allocation: 128 bytes)

julia> @btime roll2($arr, 2);
70.605 ns (4 allocations: 256 bytes)

但是请注意,建议的功能都没有就地运行。他们都创建了一个新数组。还有内置的 circshift!(dest, src, shift)它在预分配的 dest 中运行(但是,必须是 != src )。

关于julia - 滚动阵列,均匀圆形移位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53787042/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com