function - 重复应用函数特定次数

标签 function julia

如果您有一个函数,是否有简单或内置的方法来应用它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/

相关文章:

javascript - 为以后的 Javascript 保存参数

function - 为什么我传递的结构没有改变

makefile - 从源代码构建 Julia 后,可以安全删除哪些内容?

plot - Julia 中的 3D 矢量图

machine-learning - 使用 Flux.jl 进行逻辑回归

C++继承,从基类调用派生函数

r - 将函数应用于时间序列

在函数内调用数组

julia - 如何将 JuMP 约束设置为等于数组中的值?

julia - Vega-Lite - 多个数据集的一个图