我对 Julia 非常陌生,并尝试实现/重写我以前的一些 Python 代码作为练习。我使用 Project Euler Problem 25 作为练习
在Python中我有
def fibonacci(N):
"""Returns the Nth Fibonacci Number"""
F = [0, 1]
i = 0
while i <= N-2:
F_new = F[i] + F[i+1]
F.append(F_new)
i += 1
return F[N]
N = 0
x = 1000
while len(str(fibonacci(N))) <= x:
if len(str(fibonacci(N))) == x:
print(N)
break
N = N + 1
Run Code Online (Sandbox Code Playgroud)
它运行并在大约 6.5 秒内给我正确的答案。当尝试在下面的 Julia 中执行此操作时
function fib(N)
F = [0, 1]
global i = 1
while i <= N-2
F_new = F[i] + F[i+1]
append!(F, F_new)
global i += 1
end
return F[N]
end
N = 1
x = 1000
while length(string(fib(N))) <= x
if length(string(fib(N))) == x
print(N-1)
break
end
global N += 1
end
Run Code Online (Sandbox Code Playgroud)
该代码似乎“永远”运行。然而,在 Julia 代码中,只有当 x<= 20 时,代码才会完成并产生正确的答案。在 Julia 代码中,当 x>20 时,程序永远不会结束。
我不确定如果它对所有低于 21 的值运行,哪里可能会出错?有人可以解释错误发生在哪里以及为什么吗?
您的代码的主要问题是@duckboycool 所描述的。第二个建议是始终在 Julia 中编写函数。阅读Julia 性能提示页面以获得良好的开端。
\n请注意,您可以通过删除不必要的功能来使 @Bill 的功能加快 2 倍,if如下所示:
function test(x = 1000)\n N = 0\n while ndigits(fib(N)) < x\n N += 1\n end\n return N\nend\nRun Code Online (Sandbox Code Playgroud)\n但如果你真的想要一个速度快 16000 倍的 Julia 版本,那么你可以这样做:
\nfunction euler25()\n limit = big(10)^999\n a, b = big(1), big(1)\n N = 2\n while b <= limit\n a, b = b, a + b\n N += 1\n end\n return N\nend\n\n@btime euler25() = 4782\n 377.700 \xce\xbcs (9573 allocations: 1.15 MiB)\nRun Code Online (Sandbox Code Playgroud)\n这在 377 \xce\xbcs 中运行,因为我们避免从一开始就在每一步计算 fib(N)。我们不与每次迭代时输出的字符串长度进行比较,而是与 10^999 进行比较。
\n| 归档时间: |
|
| 查看次数: |
194 次 |
| 最近记录: |