Julia: 在迭代过程中是否有固定值的方法?

huangapple go评论53阅读模式
英文:

Julia: Is there a method for fixing the value in the iteration process?

问题

我正在编写代码以使用卡方拟合找到解决方案。
它涉及许多参数和大量方程式,因此时间成本非常高。
然而,一些方程和参数不需要在每次迭代中进行计算(或读取)。在第一次迭代中进行一次计算就足够了。
为了减少时间成本,我想要固定这些值,而不是交换这些值。
是否有任何方法和/或技巧可以实现这个目的?

英文:

I'm writing the code for found the solution using chi-square fitting.
It includes many parameters and massive equations, thus, the time cost is so high.
However, some equations and parameters don't need to be calculated(or read) for every iteration. Just one calculation at the first iteration is enough.
In order to reduce the time cost, I want to fix the values, on the other hand, not swap the value.
Is there any method and/or trick for this purpose?

答案1

得分: 0

我认为除了使用两个循环之外,没有其他方法。这可能有些棘手,但你可以在主(第二个)循环之外首先计算你的方程。但由于它只在第一次迭代时执行,从技术上讲,你只有一个循环,因为只有一个迭代的循环基本上是没有用的。之后,你可以在循环中使用它们。

# 在这里计算

# 循环在这里
...
...
英文:

I don't think there is any other way other than to have two loops. This may be tricky, but you can first calculate your equations outside the main (second) loop. However since it's only on the first iteration, technically you only have 1 loop as a loop with 1 iteration is basically useless. Afterwards, you can use them in the loop.

#Calculate here

#loop here
...
...

答案2

得分: 0

I think you are asking about avoiding re-computation by buffering known results. This technique is called memoization.

This can be achieved by using Memoization:

using Memoization

@memoize function myfunction(x)
    sleep(0.5)
    x .^ 2
end

Let us have a look how this works:

julia> @time myfunction(1:3)
  0.513210 seconds (6 allocations: 224 bytes)
3-element Vector{Int64}:
 1
 4
 9

julia> @time myfunction(1:3)
  0.000004 seconds
3-element Vector{Int64}:
 1
 4
 9

You can see that subsequent calls to myfunction use the memoized buffer.

英文:

I think you are asking about avoiding re-computation by buffering known results. This technique is called memoization.

This can be achieved by using Memoization:

using Memoization

@memoize function myfunction(x)
    sleep(0.5)
    x .^ 2
end

Let us have a look how this works:

julia> @time myfunction(1:3)
  0.513210 seconds (6 allocations: 224 bytes)
3-element Vector{Int64}:
 1
 4
 9

julia> @time myfunction(1:3)
  0.000004 seconds
3-element Vector{Int64}:
 1
 4
 9

You can see that subsequent calls to myfunction use the memoized buffer.

huangapple
  • 本文由 发表于 2023年1月6日 14:05:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/75027497.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定