Python和Julia的输出值不相等
我正在用 Python 和 Julia 实现 Mandelbrot 函数;然而,在第 6 次迭代之后,代码产生了不同的结果。主要原因是什么?
这是 Python 中的代码:
def mandelbrot(a):
z = 0
for i in range(50):
z = z**2 + a
return z
并且,这是 Julia 中的相同代码:
function mandelbrot(a)
z = 0
for i=1:50
z = z^2 + a
end
return z
end
回答
对于 Mandelbrot 集合中的点,这似乎不可重现:
Python 3.7.4 (default, Aug 13 2019, 15:17:50)
[Clang 4.0.1 (tags/RELEASE_401/final)] :: Anaconda, Inc. on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def mandelbrot(a):
... z = 0
... for i in range(50):
... z = z**2 + a
... return z
...
>>> mandelbrot(-0.75)
-0.40274177046812404
>>> mandelbrot(0.1)
0.11270166537925831
>>> mandelbrot(0.2)
0.2763932022500072
_
_ _ _(_)_ | Documentation: https://docs.julialang.org
(_) | (_) (_) |
_ _ _| |_ __ _ | Type "?" for help, "]?" for Pkg help.
| | | | | | |/ _` | |
| | |_| | | | (_| | | Version 1.6.1 (2021-04-23)
_/ |__'_|_|_|__'_| | Official https://julialang.org/ release
|__/ |
julia> function mandelbrot(a)
z = 0
for i=1:50
z = z^2 + a
end
return z
end
mandelbrot (generic function with 1 method)
julia> mandelbrot(-0.75)
-0.40274177046812404
julia> mandelbrot(0.1)
0.11270166537925831
julia> mandelbrot(0.2)
0.2763932022500072
到目前为止,我能够观察到的唯一区别是,对于集合之外的点,Python 可能会返回一个 OverflowError,其中 Julia 返回Inf。
_
_ _ _(_)_ | Documentation: https://docs.julialang.org
(_) | (_) (_) |
_ _ _| |_ __ _ | Type "?" for help, "]?" for Pkg help.
| | | | | | |/ _` | |
| | |_| | | | (_| | | Version 1.6.1 (2021-04-23)
_/ |__'_|_|_|__'_| | Official https://julialang.org/ release
|__/ |
julia> function mandelbrot(a)
z = 0
for i=1:50
z = z^2 + a
end
return z
end
mandelbrot (generic function with 1 method)
julia> mandelbrot(-0.75)
-0.40274177046812404
julia> mandelbrot(0.1)
0.11270166537925831
julia> mandelbrot(0.2)
0.2763932022500072
julia> mandelbrot(0.3)
Inf
大概是由于这两种语言在处理浮点特殊值(如Inf.
特别是,Python 默认情况下似乎不遵循 IEEE 754 浮点运算的标准规则,其中以下应分别返回+和- Inf(参见IEEE 754,除以零)
>>> 1.0/+0.0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: float division by zero
>>> 1.0/-0.0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: float division by zero
而朱莉娅则:
julia> 1.0/+0.0
Inf
julia> 1.0/-0.0
-Inf