Python 中的虚数

Vaibhhav Khetarpal 2023年1月30日
  1. 在 Python 中初始化一个复数
  2. 在 Python 中使用复数属性和函数
  3. 在 Python 中对复数使用常规数学运算
  4. 在复数上使用 cmath 模块函数
  5. 在 Python 中使用 numpy.array() 函数在数组中存储虚数
Python 中的虚数

Python 是一种用于处理数值数据的通用语言。它还支持处理实数和虚数。在本教程中,你将了解有关虚数以及如何在 Python 中使用它们的更多信息。

在 Python 中初始化一个复数

复数由实部和虚部组成。在 Python 中,虚部可以通过在数字后添加 jJ 来表示。

可以轻松创建复数:通过将实部和虚部直接分配给变量。下面的示例代码演示了如何在 Python 中创建复数:

a = 8 + 5j
print(type(a))

输出:

<class 'complex'>

我们还可以使用内置的 complex() 函数将两个给定的实数转换为一个复数。

a = 8
b = 5
c = complex(8, 5)
print(type(c))

输出:

<class 'complex'>

现在,文章的另一半将更多地关注在 Python 中处理虚数。

在 Python 中使用复数属性和函数

复数有一些可用于一般信息的内置访问器。

例如,要访问复数的实部,我们可以使用内置的 real() 函数,类似地使用 imag() 函数来访问虚部。此外,我们还可以使用 conjugate() 函数找到复数的共轭。

a = 8 + 5j
print("Real Part = ", a.real)
print("Imaginary Part = ", a.imag)
print("Conjugate = ", a.conjugate())

输出:

Real Part =  8.0
Imaginary Part =  5.0
Conjugate =  (8-5j)

在 Python 中对复数使用常规数学运算

你可以在 Python 中对复数进行基本的数学运算,例如加法和乘法。下面的代码在两个给定的复数上实现了简单的数学过程。

a = 8 + 5j
b = 10 + 2j

# Adding imaginary part of both numbers
c = a.imag + b.imag
print(c)

# Simple multiplication of both complex numbers
print("after multiplication = ", a * b)

输出:

7.0
after multiplication =  (70+66j)

在复数上使用 cmath 模块函数

cmath 模块是一个特殊模块,它提供对用于复数的多个函数的访问。该模块由多种功能组成。一些值得注意的是复数的相位、幂函数和对数函数、三角函数和双曲函数。

cmath 模块还包括几个常量,如 pitauPositive infinity,以及一些用于计算的常量。

以下代码在 Python 中对复数实现了一些 cmath 模块函数:

import cmath

a = 8 + 5j
ph = cmath.phase(a)

print("Phase:", ph)
print("e^a is:", cmath.exp(a))
print("sine value of complex no.:\n", cmath.sin(a))
print("Hyperbolic sine is: \n", cmath.sinh(a))

输出:

Phase: 0.5585993153435624
e^a is: (845.5850573783163-2858.5129755252788j)
sine value of complex no.:
 (73.42022455449552-10.796569647775932j)
Hyperbolic sine is: 
 (422.7924811101271-1429.2566486042679j)

在 Python 中使用 numpy.array() 函数在数组中存储虚数

术语 NumPy 是 Numerical Python 的缩写。它是 Python 提供的一个库,用于处理数组并提供对这些数组进行操作的函数。顾名思义,numpy.array() 函数用于创建数组。下面的程序演示了如何在 Python 中创建复数数组:

import numpy as np

arr = np.array([8 + 5j, 10 + 2j, 4 + 3j])
print(arr)

输出:

[8.+5.j 10.+2.j  4.+3.j]

复数是 Python 允许存储和实现数值数据的三种方式之一。它也被认为是 Python 编程的重要组成部分。你可以使用 Python 编程语言对复数执行各种操作。

Vaibhhav Khetarpal avatar Vaibhhav Khetarpal avatar

Vaibhhav is an IT professional who has a strong-hold in Python programming and various projects under his belt. He has an eagerness to discover new things and is a quick learner.

LinkedIn

相关文章 - Python Math