代码之家  ›  专栏  ›  技术社区  ›  Light_B jezrael

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

  •  1
  • Light_B jezrael  · 技术社区  · 8 年前

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

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

    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 回复  |  直到 8 年前
        1
  •  2
  •   Ben Bolker    8 年前

    你没有做错什么。虚部很小,这是不可避免的浮点不精确的结果。R和Python的区别仅仅在于 输出功率;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