如果您有一个函数,是否有简单或内置的方法来应用它n
次,或者直到结果是特定的。因此,例如,如果您想应用 sqrt
作用4次,效果:
julia> sqrt(sqrt(sqrt(sqrt(11231))))
1.791229164345863
你可以输入如下内容:
repeatf(sqrt, 11231, 4)
最佳答案
我很喜欢定义 ^
运算符(operator)处理 Function
s 和 Int
秒
julia> (^)(f::Function, i::Int) = i==1 ? f : x->(f^(i-1))(f(x))
^ (generic function with 1 method)
julia> (sqrt^1)(2)
1.4142135623730951
julia> (sqrt^2)(2)
1.189207115002721
julia> (sqrt^3)(2)
1.0905077326652577
正如@DNF 指出的,因为 julia 没有尾调用优化,最好反复执行此操作;
julia> function (∧)(f::Function, i::Int)
function inner(x)
for ii in i:-1:1
x=f(x)
end
x
end
end
After warmup:
julia> @time((sqrt ∧ 1_000)(20e300)) #Iterative
0.000018 seconds (6 allocations: 192 bytes)
1.0
julia> @time((sqrt ^ 1_000)(20e300)) #Recursive
0.000522 seconds (2.00 k allocations: 31.391 KB)
1.0
#########
julia> @time((sqrt ∧ 10_000)(20e300)) #Iterative
0.000091 seconds (6 allocations: 192 bytes)
1.0
julia> @time((sqrt ^ 10_000)(20e300)) #Recursive
0.003784 seconds (20.00 k allocations: 312.641 KB)
1.0
#########
julia> @time((sqrt ∧ 30_000)(20e300)) # Iterative
0.000224 seconds (6 allocations: 192 bytes)
1.0
julia> @time((sqrt ^ 30_000)(20e300)) #Recursive
0.008128 seconds (60.00 k allocations: 937.641 KB)
1.0
#############
julia> @time((sqrt ∧ 100_000)(20e300)) #Iterative
0.000393 seconds (6 allocations: 192 bytes)
1.0
julia> @time((sqrt ^ 100_000)(20e300)) #Recursive
ERROR: StackOverflowError:
in (::##5#6{Base.#sqrt,Int64})(::Float64) at ./REPL[1]:1 (repeats 26667 times)
The overhead isn't too bad in this case, but that `StackOverflowError` at the end is a kicker.
关于function - 重复应用函数特定次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39895672/