【问题标题】:TypeError: only length-1 arrays can be converted to Python scalars - complex numbersTypeError:只有长度为 1 的数组可以转换为 Python 标量 - 复数
【发布时间】:2019-01-24 09:25:50
【问题描述】:

我尝试使用 Python 2.7 绘制具有复杂值的图形。但是代码没有返回 y 值的复数值。

import numpy as np
import math
import cmath
import matplotlib.pyplot as plt

def f(x):
     return ((x)*cmath.sqrt((x)+0.5)*((x)+1))


x=np.linspace(-4,-2,10)
y=f(x)
plt.plot( x,y, label=fx_name)
plt.title('sample ')
plt.xlabel('X')
plt.ylabel('Y')
plt.legend(loc='upper left')
plt.show()

错误是

    Traceback (most recent call last):
  File "/home/Happy/Demo/code10.py", line 12, in <module>
    y=f(x)
  File "/home/Happy/Demo/code10.py", line 7, in f
    return ((x)*cmath.sqrt((x)+0.5)*((x)+1))
TypeError: only length-1 arrays can be converted to Python scalars

【问题讨论】:

  • 尝试将cmath.sqrt 替换为np.sqrt。并且您需要将x 转换为complex 类型,即x.astype(complex)
  • 你似乎在寻找负数的平方根。
  • 是的。这就是输出产生错误的原因
  • x = x.astype(np.complex128); return x*np.sqrt(x+0.5)*(x+1)
  • 问题是cmathmath 一样只适用于标量值。您的 x 是一个数组,有 10 个值,而不仅仅是一个。

标签: python python-2.7 numpy matplotlib math


【解决方案1】:

用 numpy 试试:

import numpy as np
import matplotlib.pyplot as plt


def f(x):
    return ((x) * np.sqrt((x) + 0.5) * ((x) + 1))


x = np.linspace(-4, -2, 10).astype(np.complex)
y = f(x)

plt.plot(y.real, y.imag,'*')
for i in range(x.shape[0]):
    plt.text(y.real[i], y.imag[i],"x="+str(x.real[i]))
plt.title('sample')
plt.xlabel('y real')
plt.ylabel('y imag')
plt.show()

【讨论】:

    猜你喜欢
    • 2014-09-27
    • 2013-03-15
    • 2016-08-06
    • 2018-09-14
    • 1970-01-01
    • 1970-01-01
    • 2015-02-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多