Python与R / Matlab的复数指数实现

时间:2018-11-08 15:13:42

标签: python r complex-numbers

在Python vs R中实现这种简单计算时,我面临着不同的结果

e ^(2 * pi * 1j)= cos(2 * pi)+ j * sin(2 * pi)= 1

在R中,它给出了预期的结果

j   <- complex(real = 0, imaginary = 1)
exp(2*pi*j)
>>1 -0j

Python中的

import math
import cmath

cmath.exp(2*math.pi*1j)
>>(1-2.4492935982947064e-16j)
## Also tried this
math.e ** (2*math.pi*1j)
>>(1-2.4492935982947064e-16j)

在Python中实现该功能时我会做错什么?

1 个答案:

答案 0 :(得分:2)

您没有做错任何事情。虚部很小,这是不可避免的浮点不精确性的结果。 R和Python之间的区别仅在于输出的 representation ; R(最初设计为交互式统计分析的平台)没有显示非常小的虚构部分,但仍然存在:

j   <- complex(real = 0, imaginary = 1)
> exp(2*pi*j)
[1] 1-0i
> Im(exp(2*pi*j))
[1] -2.449294e-16
print(Im(exp(2*pi*j)),digits=22)
[1] -2.449293598294706414348e-16