DEV Community

codemee
codemee

Posted on • Edited on

3

Python 的虛數 j

在 Python 中是使用 j 作為虛數單位, 但 j 也可以用來當識別字, 因此使用上要特別注意。

一定要加上數量

使用虛數時, j 的前面一定要有數量, 例如, 要計算 1j×1j 就一定要寫成:

>>> 1j * 1j
(-1+0j)
Enter fullscreen mode Exit fullscreen mode

數量甚至可以是 0:

>>> 0j
0j
Enter fullscreen mode Exit fullscreen mode

如果沒有數量, 只有 j, 就會被當成一般的識別字:

>>> j
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'j' is not defined

name 'j' is not defined
Enter fullscreen mode Exit fullscreen mode

別用 j 當識別字

當然, 你也可以把 j 真的拿來當識別字使用, 例如:

>>> j = 1j
>>> j
1j
Enter fullscreen mode Exit fullscreen mode

只是當然這並不是好作法, 既容易混淆, 也不容易看懂, 所以最好不要這樣做。

用括號不嫌煩地把複數括起來

將 j 應用在複數時, 請記得用括號將實部與虛部節合在一起, 避免會當成是一個實數和一個只有虛部的複數, 例如以下就會算出錯誤的結果:

>>> 1+2j.imag
3.0
Enter fullscreen mode Exit fullscreen mode

原本想要計算複數 1+2j 的虛部, 結果因為 . 的優先權大於 +, 導致結果變成 1+(2j.imag) 了。如果不嫌麻煩加上括號就不會出錯:

>>> (1+2j).imag
2.0
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more