在 julia 中绘制浮点数组
Plotting an float array in julia
我有以下代码
using Plots
function test()::nothing
A::Array{Float64,1} = rand(Float64,100)
plot(A)
end
我运行在朱莉娅这样
julia> include("main.jl")
test (generic function with 1 method)
julia> test()
ERROR: MethodError: First argument to `convert` must be a Type, got nothing
Stacktrace:
[1] test() at /path/to/main.jl:85
[2] top-level scope at REPL[2]:1
为什么我会收到错误 First argument to convert must be a Type, got nothing
?
好吧,这个问题与您在注释中使用 nothing
,但正确的类型是 Nothing
(注意大写 N
)有关。 nothing
是一个对象,Nothing
是这个对象的类型。
所以你应该使用像
这样的东西
function test()::Nothing
A::Array{Float64,1} = rand(Float64, 100)
display(plot(A))
nothing
end
请注意,我必须添加 nothing
作为 return 值和明确的 display
以显示实际情节。
但是,老实说,主要问题不是Nothing
,而是过度专业化。函数中的类型注释不会加快计算速度,您应该只在真正需要时才使用它们,例如在多重分派中。
惯用代码如下所示
function test()
A = rand(100)
plot(A)
end
请注意,我在 rand
中删除了所有额外的注释和不必要的 Float64
,因为它是默认值。
我有以下代码
using Plots
function test()::nothing
A::Array{Float64,1} = rand(Float64,100)
plot(A)
end
我运行在朱莉娅这样
julia> include("main.jl")
test (generic function with 1 method)
julia> test()
ERROR: MethodError: First argument to `convert` must be a Type, got nothing
Stacktrace:
[1] test() at /path/to/main.jl:85
[2] top-level scope at REPL[2]:1
为什么我会收到错误 First argument to convert must be a Type, got nothing
?
好吧,这个问题与您在注释中使用 nothing
,但正确的类型是 Nothing
(注意大写 N
)有关。 nothing
是一个对象,Nothing
是这个对象的类型。
所以你应该使用像
这样的东西function test()::Nothing
A::Array{Float64,1} = rand(Float64, 100)
display(plot(A))
nothing
end
请注意,我必须添加 nothing
作为 return 值和明确的 display
以显示实际情节。
但是,老实说,主要问题不是Nothing
,而是过度专业化。函数中的类型注释不会加快计算速度,您应该只在真正需要时才使用它们,例如在多重分派中。
惯用代码如下所示
function test()
A = rand(100)
plot(A)
end
请注意,我在 rand
中删除了所有额外的注释和不必要的 Float64
,因为它是默认值。