You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用cmath绘制以i为底的对数函数时遇TypeError错误求助

解决以i为底的对数函数绘图错误

错误原因

cmath.log 是Python标准库的函数,仅支持处理单个复数标量,无法直接接收numpy数组作为输入,这就是你遇到 TypeError: only length-1 arrays can be converted to Python scalars 错误的原因。

解决方案

方法1:用numpy.vectorize包装cmath.log

通过numpy.vectorize将仅支持标量的cmath.log转换为可处理numpy数组的函数:

from pylab import *
import cmath

# 包装cmath.log,使其支持数组输入
log_base_i = np.vectorize(lambda num: cmath.log(num, 1j))

x = linspace(-8, 8, 500)
z = log_base_i(x)

plot(x, real(z), label='real')
plot(x, imag(z), label='imag')
legend()
show()

方法2:利用对数换底公式(推荐)

根据对数换底公式 log_b(a) = ln(a)/ln(b),直接使用numpy的向量化对数函数计算,效率比vectorize更高:

from pylab import *

x = linspace(-8, 8, 500)
# 计算log_i(x) = np.log(x) / np.log(1j)
z = np.log(x) / np.log(1j)

plot(x, np.real(z), label='real')
plot(x, np.imag(z), label='imag')
legend()
show()

注:np.log(1j) 的值为 1.5707963267948966j(即 jπ/2),符合复数对数的定义。

内容的提问来源于stack exchange,提问作者ADrakkar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 20:05:36