在C(++)中,我可以在头文件myFLOAT.h中完成
typedef myFLOAT double;
// typedef myFLOAT BigFloat; // with the correct lib然后,我可以编写基于myFLOAT类型的代码,并且只需取消注释/注释头文件中相应的行,就可以非常容易地在double和BigFloat之间切换。
我如何在Julia中做同样的事情?
我试过了
abstract type myFLOAT <: Float64 end
#abstract type myFLOAT <: BigFloat end但我得到了
ERROR: invalid subtyping in definition of myFLOAT我在@clbieganek的答案后面添加了以下注释
我的模拟代码通常如下所示
init = initSimulation(args);
result = doSimulation(init);
Plotting(result); 我同意我可以/应该在doSimulation()中使用AbstractFloat "everywhere“。但是有了
const myFLOAT = Float64 # thanks我想保证“struct init”中的每个myFLOAT都是一个Float64或BigFloat,具体取决于用例。这样'doSimulation(init)‘将选择正确的浮点类型。
发布于 2019-05-09 01:21:15
在Julia中,具体类型不能为子类型。Float64和BigFloat都是具体的类型,这就是为什么会出现invalid子类型错误的原因。您尝试做的事情的直接转换是创建类型别名:
const MyType = Float64但是,Julian方法是使用尽可能多的泛型类型来定义类型和方法。在您的例子中,您可以使用AbstractFloat。然后,您的代码将同时适用于Float64和BigFloat。例如,
julia> struct A
x::AbstractFloat
end
julia> function foo(a::A, x::AbstractFloat)
return a.x + x
end
foo (generic function with 1 method)
julia> a1 = A(4.5)
A(4.5)
julia> foo(a1, 5.2)
9.7
julia> a2 = A(BigFloat(4.5))
A(4.5)
julia> foo(a2, BigFloat(5.2))
9.70000000000000017763568394002504646778106689453125数字的Julia类型层次结构可以是viewed here。
发布于 2019-05-09 01:24:00
您可以对函数使用where语法,并使用T、then等语法:
julia> function f(a::T) where T <: Number
ret = zeros(T, 5, 5)
ret
end
f (generic function with 1 method)
julia> x = 1.0
1.0
julia> f(x)
5×5 Array{Float64,2}:
0.0 0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0 0.0
julia> y = BigFloat(1.0)
1.0
julia> f(y)
5×5 Array{BigFloat,2}:
0.0 0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0 0.0
julia>https://stackoverflow.com/questions/56044955
复制相似问题