【发布时间】:2020-10-31 16:12:57
【问题描述】:
我定义了一个函数如下:
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))
我不知道如何实现这一点。
【问题讨论】:
-
这样做的目的是什么?
tot应该是一个整数,通常是一个Int64。你为什么要它是一个浮点数?tot总是小于n,这也是一个Int64。让它们漂浮没有任何目的。