gpt4 book ai didi

generics - Julia 泛型函数类型参数

转载 作者:行者123 更新时间:2023-12-03 18:43:13 25 4
gpt4 key购买 nike

我定义了一个函数如下:

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 中是一等公民,因此您可以像使用任何其他值一样将它们用作函数参数。
例如,在这种情况下,您可以简单地将所需类型指定为附加参数:

julia> function approx_pi(T, n)
tot = zero(T) # Better than T(0)
for i in 1:n
x = rand(T) # Not sure whether you want these to be of
y = rand(T) # type T, or remain as Float64
if x^2 + y^2 < 1
tot+=1
end
end
tot / n * 4
end
approx_pi (generic function with 1 method)

julia> approx_pi(BigFloat, 1_000_000)
3.141276000000000000000000000000000000000000000000000000000000000000000000000003

关于generics - Julia 泛型函数类型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64623810/

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