gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 01:27:38 24 4
gpt4 key购买 nike

在 Python 和 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 实现它时做错了什么?

最佳答案

你没有做错任何事。虚部很小,这是不可避免的浮点不精确的结果。 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

关于复数指数的 Python 与 R/Matlab 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53210643/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com