最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python復(fù)數(shù)類型complex應(yīng)用場(chǎng)景詳解

 更新時(shí)間:2026年06月22日 09:51:13   作者:星河耀銀海  
Python內(nèi)置支持復(fù)數(shù)類型,使用a+bj的形式表示,支持基本算術(shù)運(yùn)算、比較相等性操作,Python通過(guò)cmath模塊提供了豐富的復(fù)數(shù)數(shù)學(xué)函數(shù),感興趣的可以了解一下

一、開篇:Python內(nèi)置復(fù)數(shù)——一個(gè)被低估的特性

如果你不是數(shù)學(xué)或物理專業(yè)的,可能從高中畢業(yè)后就沒(méi)再接觸過(guò)復(fù)數(shù)。你可能會(huì)想:“我寫程序永遠(yuǎn)用不到復(fù)數(shù)吧?”

不一定。復(fù)數(shù)在信號(hào)處理、圖像處理、電子電路仿真、量子計(jì)算、3D圖形學(xué)等領(lǐng)域都有實(shí)際應(yīng)用。而Python是為數(shù)不多的內(nèi)置復(fù)數(shù)類型的主流編程語(yǔ)言——在很多語(yǔ)言中你需要引入第三方庫(kù)才能處理復(fù)數(shù)。

?? 這篇文章有兩個(gè)目的:一是讓你了解Python中的復(fù)數(shù)怎么用,二是讓你知道它在什么場(chǎng)景下有用。即使你平時(shí)用不到,了解Python有這個(gè)內(nèi)置能力也是一件好事。

二、復(fù)數(shù)的數(shù)學(xué)基礎(chǔ)回顧

2.1 5分鐘復(fù)習(xí)復(fù)數(shù)

復(fù)數(shù)由兩部分組成:實(shí)部(real part)虛部(imaginary part)。形如:

a + bj (在數(shù)學(xué)中通常寫作 a + bi,Python中用 j 代替 i)

其中:

  • a 是實(shí)部(一個(gè)實(shí)數(shù))
  • b 是虛部系數(shù)(一個(gè)實(shí)數(shù))
  • j 是虛數(shù)單位,滿足 j² = -1
# Python中的復(fù)數(shù)
z1 = 3 + 4j       # 實(shí)部=3, 虛部=4
z2 = 1 - 2j       # 實(shí)部=1, 虛部=-2
z3 = 5j           # 純虛數(shù),實(shí)部=0(注意:不能寫成 j5)
z4 = 2 + 0j       # 其實(shí)就是實(shí)數(shù)2(但類型是complex)

?? 注意:Python中使用 j 而不是數(shù)學(xué)中的 i 來(lái)表示虛數(shù)單位。這是工程領(lǐng)域的慣例(因?yàn)?i 常被用作電流的符號(hào))。

三、Python中復(fù)數(shù)的創(chuàng)建

3.1 字面量方式

# 基本創(chuàng)建
a = 3 + 4j
b = -1 - 2j
c = 5j           # 等于 0 + 5j
d = 2 - 0j       # 等于 2 + 0j

# 注意:虛部系數(shù)必須緊挨著j
# e = 1 + j      # NameError!j被當(dāng)作變量名
e = 1 + 1j       # OK

3.2 使用complex()函數(shù)

# 從一個(gè)參數(shù)
z1 = complex(5)         # (5+0j)
z2 = complex(3.14)      # (3.14+0j)

# 從兩個(gè)參數(shù)(實(shí)部, 虛部)
z3 = complex(3, 4)      # (3+4j)
z4 = complex(-1, 2.5)   # (-1+2.5j)

# 從字符串(不能有空格?。?
z5 = complex('3+4j')    # (3+4j)
z6 = complex('-1-2j')   # (-1-2j)
z7 = complex('5j')      # 5j
z8 = complex('3')       # (3+0j)

# 這些會(huì)報(bào)錯(cuò)
# complex('3 + 4j')     # 字符串中有空格!
# complex('3+4i')       # Python用j,不是i

3.3 獲取實(shí)部和虛部

z = 3 + 4j

print(z.real)    # 3.0(注意:返回float類型)
print(z.imag)    # 4.0

# 復(fù)數(shù)的共軛(虛部取反)
print(z.conjugate())  # (3-4j)

四、復(fù)數(shù)的運(yùn)算

4.1 基本算術(shù)運(yùn)算

a = 3 + 4j
b = 1 - 2j

# 加法:(3+4j) + (1-2j) = 4+2j
print(a + b)     # (4+2j)

# 減法:(3+4j) - (1-2j) = 2+6j
print(a - b)     # (2+6j)

# 乘法:(3+4j)(1-2j) = 3-6j+4j-8j2 = 3-2j+8 = 11-2j
print(a * b)     # (11-2j)

# 除法:(3+4j)/(1-2j)
print(a / b)     # (-1+2j)

# 冪運(yùn)算
print(a ** 2)    # (-7+24j) — 因?yàn)?(3+4j)2 = 9+24j+16j2 = 9+24j-16 = -7+24j

4.2 比較運(yùn)算

a = 3 + 4j
b = 3 + 4j

# 可以比較相等
print(a == b)    # True
print(a != b)    # False

# 不能比較大??!
# print(a > b)   # TypeError: '>' not supported between complex numbers
# print(a < b)   # 同上

?? 復(fù)數(shù)不能比較大小——這在數(shù)學(xué)上就沒(méi)有意義。復(fù)數(shù)之間只能判斷相等或不等。

4.3 內(nèi)置函數(shù)對(duì)復(fù)數(shù)的支持

import math
import cmath  # 復(fù)數(shù)的數(shù)學(xué)函數(shù)

z = 3 + 4j

# abs():復(fù)數(shù)的模(magnitude)
# |3+4j| = sqrt(32 + 42) = sqrt(25) = 5
print(abs(z))              # 5.0

# pow():冪運(yùn)算
print(pow(z, 2))           # (-7+24j)

# round()不能用于復(fù)數(shù)
# round(z)  # TypeError

# cmath模塊:復(fù)數(shù)的數(shù)學(xué)函數(shù)
print(cmath.sqrt(z))       # (2+1j)(因?yàn)?2+j)2 = 4+4j+j2 = 3+4j)

# 復(fù)數(shù)的極坐標(biāo)表示
print(cmath.polar(z))      # (5.0, 0.9272952180016122)
# 返回 (模, 輻角) = (5.0, arctan(4/3))

# 從極坐標(biāo)恢復(fù)復(fù)數(shù)
modulus, angle = 5.0, 0.9272952180016122
print(cmath.rect(modulus, angle))  # (3+4j)

# 歐拉公式:e^(jx) = cos(x) + j*sin(x)
x = 0.5
print(cmath.exp(1j * x))  # (0.87758+0.47943j)
print(complex(cmath.cos(x), cmath.sin(x)))  # 手動(dòng)計(jì)算驗(yàn)證

4.4 cmath模塊常用函數(shù)

import cmath

z = 1 + 1j

# 指數(shù)和對(duì)數(shù)
print(cmath.exp(z))       # e^z
print(cmath.log(z))       # ln(z)
print(cmath.log10(z))     # log10(z)

# 三角函數(shù)
print(cmath.sin(z))
print(cmath.cos(z))
print(cmath.tan(z))

# 反三角函數(shù)
print(cmath.asin(z))
print(cmath.acos(z))
print(cmath.atan(z))

# 雙曲函數(shù)
print(cmath.sinh(z))
print(cmath.cosh(z))
print(cmath.tanh(z))

# 判斷函數(shù)
print(cmath.isinf(complex(float('inf'), 0)))   # True
print(cmath.isnan(complex(float('nan'), 0)))   # True
print(cmath.isclose(1+2j, 1+2.0000000001j))    # True

五、復(fù)數(shù)的實(shí)際應(yīng)用場(chǎng)景

5.1 信號(hào)處理:傅里葉變換

import cmath

def discrete_fourier_transform(samples):
    """
    離散傅里葉變換(DFT)
    輸入:時(shí)域信號(hào)采樣點(diǎn)列表(實(shí)數(shù))
    輸出:頻域復(fù)數(shù)列表
    """
    n = len(samples)
    result = []
    for k in range(n):
        # 計(jì)算第k個(gè)頻率分量
        frequency_component = 0j
        for t in range(n):
            angle = -2 * cmath.pi * 1j * k * t / n
            frequency_component += samples[t] * cmath.exp(angle)
        result.append(frequency_component)
    return result


# 示例:分析一個(gè)包含兩個(gè)頻率成分的信號(hào)
import math

# 生成采樣信號(hào):50Hz + 120Hz的正弦波
sample_rate = 500  # 采樣率
duration = 1.0     # 1秒
n_samples = int(sample_rate * duration)

samples = []
for i in range(n_samples):
    t = i / sample_rate
    value = math.sin(2 * math.pi * 50 * t) + 0.5 * math.sin(2 * math.pi * 120 * t)
    samples.append(value)

# 執(zhí)行DFT
frequency_spectrum = discrete_fourier_transform(samples)

# 顯示前10個(gè)頻率分量的幅度
print('頻率分析結(jié)果:')
for i in range(10):
    magnitude = abs(frequency_spectrum[i])
    frequency = i * sample_rate / n_samples
    print(f'{frequency:.0f}Hz: 幅度={magnitude:.2f}')

5.2 圖像處理:復(fù)數(shù)表示像素值

# 在圖像處理中,可以使用復(fù)數(shù)來(lái)表示二維坐標(biāo)系中的點(diǎn)
# 復(fù)數(shù)的實(shí)部表示x坐標(biāo),虛部表示y坐標(biāo)

def rotate_point(x, y, angle_degrees):
    """用復(fù)數(shù)實(shí)現(xiàn)二維平面上的點(diǎn)旋轉(zhuǎn)"""
    # 創(chuàng)建表示點(diǎn)的復(fù)數(shù)
    point = complex(x, y)

    # 創(chuàng)建旋轉(zhuǎn)因子:e^(jθ) = cos(θ) + j*sin(θ)
    import math
    angle_radians = math.radians(angle_degrees)
    rotation = complex(math.cos(angle_radians), math.sin(angle_radians))

    # 旋轉(zhuǎn):復(fù)數(shù)乘法
    rotated = point * rotation

    return rotated.real, rotated.imag


# 測(cè)試:將點(diǎn)(1, 0)旋轉(zhuǎn)90度
x, y = rotate_point(1, 0, 90)
print(f'(1, 0)旋轉(zhuǎn)90度后:({x:.2f}, {y:.2f})')  # (0.00, 1.00)

# 放大/縮小
def scale_point(x, y, factor):
    """縮放點(diǎn)"""
    point = complex(x, y)
    scaled = point * factor
    return scaled.real, scaled.imag

x, y = scale_point(3, 4, 2)
print(f'(3, 4)放大2倍:({x}, {y})')  # (6.0, 8.0)

5.3 電路分析:阻抗計(jì)算

# 在交流電路分析中,阻抗(電阻+電抗)用復(fù)數(shù)表示
# Z = R + jX
# R:電阻(實(shí)部),X:電抗(虛部)
# 電感:X_L = jωL,電容:X_C = 1/(jωC) = -j/(ωC)

def impedance_resistor(r):
    """純電阻阻抗"""
    return complex(r, 0)

def impedance_inductor(inductance, frequency):
    """電感阻抗:Z_L = jωL"""
    omega = 2 * 3.14159 * frequency
    return complex(0, omega * inductance)

def impedance_capacitor(capacitance, frequency):
    """電容阻抗:Z_C = 1/(jωC)"""
    omega = 2 * 3.14159 * frequency
    return complex(0, -1 / (omega * capacitance))

def parallel_impedance(z1, z2):
    """并聯(lián)阻抗"""
    return (z1 * z2) / (z1 + z2)

def series_impedance(*impedances):
    """串聯(lián)阻抗"""
    return sum(impedances)


# 示例:RLC串聯(lián)電路
R = 100.0            # 100歐姆電阻
L = 0.1              # 100毫亨電感
C = 10e-6            # 10微法電容
f = 1000.0           # 1000Hz頻率

Z_R = impedance_resistor(R)
Z_L = impedance_inductor(L, f)
Z_C = impedance_capacitor(C, f)

Z_total = series_impedance(Z_R, Z_L, Z_C)
print(f'總阻抗:{Z_total}')
print(f'阻抗模:{abs(Z_total):.2f}歐姆')
print(f'相位角:{cmath.phase(Z_total):.2f}弧度')

5.4 分形生成:曼德勃羅集

def mandelbrot(c, max_iterations=100):
    """
    判斷一個(gè)復(fù)數(shù)c是否屬于曼德勃羅集
    返回迭代次數(shù)(用于著色),如果在max_iterations內(nèi)不發(fā)散則返回max_iterations
    """
    z = 0j
    for n in range(max_iterations):
        z = z * z + c
        if abs(z) > 2:
            return n
    return max_iterations


def generate_mandelbrot(width=80, height=40, max_iter=50):
    """生成曼德勃羅集的ASCII藝術(shù)"""
    x_min, x_max = -2.0, 1.0
    y_min, y_max = -1.0, 1.0

    for y in range(height):
        line = ''
        for x in range(width):
            # 將像素坐標(biāo)映射到復(fù)數(shù)平面
            real = x_min + (x / width) * (x_max - x_min)
            imag = y_min + (y / height) * (y_max - y_min)
            c = complex(real, imag)

            # 計(jì)算這個(gè)點(diǎn)屬于曼德勃羅集的程度
            m = mandelbrot(c, max_iter)

            # 用不同字符表示不同深度
            if m == max_iter:
                line += '#'
            elif m > max_iter * 0.8:
                line += '*'
            elif m > max_iter * 0.5:
                line += '+'
            elif m > max_iter * 0.2:
                line += '.'
            else:
                line += ' '
        print(line)

# 生成曼德勃羅集(終端中的ASCII藝術(shù))
generate_mandelbrot(100, 40)

六、復(fù)數(shù)的類型轉(zhuǎn)換

# 復(fù)數(shù) → 其他類型
z = 3 + 4j

# 復(fù)數(shù) → 字符串
print(str(z))        # '(3+4j)'

# 復(fù)數(shù) → 整數(shù)/浮點(diǎn)數(shù)?不行
# int(z)             # TypeError
# float(z)           # TypeError

# 但可以取模
magnitude = abs(z)   # 5.0(float類型)

# 其他類型 → 復(fù)數(shù)
print(complex(5))           # (5+0j)
print(complex(3.14))        # (3.14+0j)
print(complex(3, 4))        # (3+4j)
print(complex('1+2j'))      # (1+2j)

七、使用復(fù)數(shù)的注意事項(xiàng)

7.1 虛部符號(hào)問(wèn)題

import cmath

# 對(duì)負(fù)數(shù)開方
# math.sqrt(-1)  # ValueError
result = cmath.sqrt(-1)   # 1j
print(result)

# 但cmath.sqrt返回復(fù)數(shù)
print(cmath.sqrt(4))      # (2+0j)——即使結(jié)果是實(shí)數(shù),也返回complex類型
print(cmath.sqrt(-4))     # 2j——令人困惑的寫法,實(shí)際是0+2j

# 如果你想要實(shí)數(shù),需要檢查
def safe_sqrt(x):
    """安全開方:正數(shù)返回float,負(fù)數(shù)返回complex"""
    if x >= 0:
        import math
        return math.sqrt(x)
    else:
        return cmath.sqrt(x)

print(safe_sqrt(4))    # 2.0
print(safe_sqrt(-4))   # 2j

7.2 復(fù)數(shù)的實(shí)部和虛部都是float

z = 3 + 4j
print(type(z.real))  # <class 'float'>
print(type(z.imag))  # <class 'float'>

# 這意味著實(shí)部或虛部也可以是float中的特殊值
z1 = complex(float('inf'), 0)   # (inf+0j)
z2 = complex(0, float('nan'))   # (nanj)
print(z1, z2)

八、本篇小節(jié)

? Python內(nèi)置復(fù)數(shù)類型——一個(gè)你可能不常用到但在需要時(shí)非常方便的特性:

  1. 創(chuàng)建方式:字面量 3+4jcomplex(3, 4)complex('3+4j')
  2. 基本運(yùn)算:加減乘除、冪運(yùn)算都支持,但不能比較大小
  3. cmath模塊:提供復(fù)數(shù)的sin、cos、exp、log、sqrt等函數(shù)
  4. 實(shí)際應(yīng)用:信號(hào)處理(傅里葉變換)、圖像旋轉(zhuǎn)、電路分析、分形生成
  5. 注意點(diǎn):虛部系數(shù)必須緊挨j(4j而不是4 j)、Python用j不是i

?? 復(fù)數(shù)是Python"內(nèi)置電池"理念的又一個(gè)體現(xiàn)。你可能90%的日常開發(fā)中用不到它,但當(dāng)你的項(xiàng)目涉及信號(hào)處理、科學(xué)計(jì)算或圖形學(xué)的時(shí)候,Python不用你額外裝任何庫(kù)就能搞定復(fù)數(shù)運(yùn)算。下一篇我們來(lái)學(xué)習(xí)布爾類型bool。

到此這篇關(guān)于Python復(fù)數(shù)類型complex應(yīng)用場(chǎng)景詳解的文章就介紹到這了,更多相關(guān)Python復(fù)數(shù)類型complex內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • python跨文件使用全局變量的實(shí)現(xiàn)

    python跨文件使用全局變量的實(shí)現(xiàn)

    這篇文章主要介紹了python跨文件使用全局變量的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2020-11-11
  • python smtplib模塊自動(dòng)收發(fā)郵件功能(二)

    python smtplib模塊自動(dòng)收發(fā)郵件功能(二)

    這篇文章主要為大家詳細(xì)介紹了python smtplib模塊自動(dòng)收發(fā)郵件功能的第二篇,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-05-05
  • nohup后臺(tái)啟動(dòng)Python腳本,log不刷新的解決方法

    nohup后臺(tái)啟動(dòng)Python腳本,log不刷新的解決方法

    今天小編就為大家分享一篇nohup后臺(tái)啟動(dòng)Python腳本,log不刷新的解決方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2019-01-01
  • python中pygame模塊用法實(shí)例

    python中pygame模塊用法實(shí)例

    這篇文章主要介紹了python中pygame模塊用法實(shí)例,通過(guò)圖形繪制來(lái)簡(jiǎn)單講述了pygame模塊的用法,具有很好的參考借鑒價(jià)值,需要的朋友可以參考下
    2014-10-10
  • python里面單雙下劃線的區(qū)別詳解

    python里面單雙下劃線的區(qū)別詳解

    本文主要介紹了python里面單雙下劃線的區(qū)別詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2023-04-04
  • Python contextlib模塊使用示例

    Python contextlib模塊使用示例

    這篇文章主要介紹了Python contextlib模塊使用示例,本文著重使用contextlib模塊產(chǎn)生一個(gè)上下文管理器,需要的朋友可以參考下
    2015-02-02
  • pycharm安裝中文插件的2種方法圖文詳解

    pycharm安裝中文插件的2種方法圖文詳解

    PyCharm可以說(shuō)是當(dāng)今最流行的一款Python?IDE了,下面這篇文章主要給大家介紹了關(guān)于pycharm安裝中文插件的2種方法,文中通過(guò)圖文介紹的非常詳細(xì),需要的朋友可以參考下
    2023-06-06
  • Python爬蟲抓取豆瓣TOP250數(shù)據(jù)從分析到實(shí)踐的全過(guò)程(詳細(xì)圖解)

    Python爬蟲抓取豆瓣TOP250數(shù)據(jù)從分析到實(shí)踐的全過(guò)程(詳細(xì)圖解)

    本文介紹了使用Python爬取豆瓣電影Top250數(shù)據(jù)的方法,首先驗(yàn)證了目標(biāo)數(shù)據(jù)在頁(yè)面源代碼中,然后通過(guò)requests模塊獲取頁(yè)面內(nèi)容,添加請(qǐng)求頭繞過(guò)反爬機(jī)制,接著使用re模塊編寫正則表達(dá)式,采用惰性匹配模式提取信息,通過(guò)循環(huán)實(shí)現(xiàn)翻頁(yè)爬取,將10頁(yè)共250條數(shù)據(jù)保存為CSV文件
    2025-10-10
  • Python多進(jìn)程通信Queue、Pipe、Value、Array實(shí)例

    Python多進(jìn)程通信Queue、Pipe、Value、Array實(shí)例

    這篇文章主要介紹了Python多進(jìn)程通信Queue、Pipe、Value、Array實(shí)例,queue和pipe用來(lái)在進(jìn)程間傳遞消息、Value + Array 是python中共享內(nèi)存映射文件的方法,需要的朋友可以參考下
    2014-11-11
  • scrapy爬蟲完整實(shí)例

    scrapy爬蟲完整實(shí)例

    這篇文章主要介紹了scrapy爬蟲完整實(shí)例,小編覺(jué)得還是挺不錯(cuò)的,具有一定借鑒價(jià)值,需要的朋友可以參考下
    2018-01-01

最新評(píng)論

昌都县| 金阳县| 牙克石市| 汉中市| 水城县| 昌黎县| 屯门区| 贵定县| 梅河口市| 平顶山市| 富民县| 定远县| 乐东| 漳平市| 溧水县| 登封市| 高密市| 台江县| 漳平市| 宜黄县| 汽车| 巴南区| 海丰县| 通州区| 浦城县| 阿拉善右旗| 阿拉善盟| 苍南县| 阳江市| 鄂州市| 临沭县| 汉源县| 来宾市| 石河子市| 肥西县| 库伦旗| 陆河县| 突泉县| 宜黄县| 荣昌县| 桦南县|