我定义了一个函数如下:
function approx_pi(n)
tot = Float64(0.0)
for i in 1:n
x = rand()
y = rand()
if x^2 + y^2 < 1
tot+=1
end
end
tot / n * 4
end
println(approx_pi(100_000_000))
我想使用相同的函数,但返回 Float128:
using Quadmath
function approx_pi(n)
tot = Float128(0.0)
for i in 1:n
x = rand()
y = rand()
if x^2 + y^2 < 1
tot+=1
end
end
tot / n * 4
end
println(approx_pi(100_000_000))
我认为有一种方法可以通过相当于 C# 或 Java 泛型来实现这一点:
function approx_pi{T}(n)
...
end
println(approx_pi{Float128}(100_000_000))
我不知道如何实现这一目标。
正如所说,您可以滥用 Julia 类型系统,但这非常不惯用,永远不应该在实践中使用。
struct ApproxPi{T} end
function ApproxPi{T}(n) where T
tot = zero(T)
for i in 1:n
x = rand(T)
y = rand(T)
if x^2 + y^2 < 1
tot+=1
end
end
tot / n * 4
end
julia> ApproxPi{Float32}(100_000)
3.14144f0
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)