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

>>> mandelbrot(0.3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in mandelbrot
OverflowError: (34, 'Result too large')
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是这样做的:

julia> 1.0/+0.0
Inf
julia> 1.0/-0.0
-Inf

最新更新