gpt4 book ai didi

Julia 内置函数求和数组?

转载 作者:行者123 更新时间:2023-12-04 10:47:16 29 4
gpt4 key购买 nike

在 Julia 中是否没有内置函数来对数字数组求和?

x = rand(10)
sum(x) # or sum(x, 1)

ERROR: MethodError: objects of type Float64 are not callable

我的意思是我可以写一个 for 循环来总结如下,
sum = 0.0    
for i in 1:length(x)
sum += x[i]
end

但如果 julia 没有把这个内置在某个地方,我会感到惊讶吗?

最佳答案

@Michael K. Borregaard提到,您重新分配了变量 sum (默认从 Base 导出),值为 Float64在某一点。当您重述 session 时,sum又是 Base.sum默认,即:

julia> x = rand(10)         
10-element Array{Float64,1}:
0.661477
0.275701
0.799444
0.997623
0.731693
0.557694
0.833434
0.90498
0.589537
0.382349

julia> sum
sum (generic function with 16 methods)

julia> sum(x)
6.733930084133119

julia> @which sum(x)
sum(a) in Base at reduce.jl:359

注意警告:

julia> original_sum = sum
sum (generic function with 16 methods)

julia> sum = x[1]
WARNING: imported binding for sum overwritten in module Main
0.6614772171381087

julia> sum(x)
ERROR: MethodError: objects of type Float64 are not callable

julia> sum = original_sum
sum (generic function with 16 methods)

julia> sum(x)
6.733930084133119

关于Julia 内置函数求和数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45407803/

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