Julia中用于数组求和的内置函数?

9
在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

但如果朱莉娅没有这个功能内置在某处,那就让我感到惊讶了。
2个回答

16

正如 @Michael K. Borregaard 提到的那样,您在某个时候将由 Base 默认导出的变量 sum 重新赋值为一个 Float64 值。当您重新启动会话时,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  

-4

无论出于何种原因,我重新启动了Julia并且sum()函数正常工作了,并且我无法再次复现相同的错误。我怀疑这与一些内存问题有关,因为我一直在存储大型数据框而没有释放内存,但实际上我不知道发生了什么。


9
您可能在会话中使用了“sum”作为变量,例如sum = 10. 这就是错误消息告诉您的内容。 - Michael K. Borregaard

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接