【问题标题】:TypeError: only length-1 arrays can be converted to Python scalars, why?TypeError:只有长度为 1 的数组可以转换为 Python 标量,为什么?
【发布时间】:2019-04-22 20:32:59
【问题描述】:

我想要一个频率函数的相位图形,但是如果我运行我的代码,输出会给我一个类型错误 f = np.arange(1,1000000) faseverschuiving_functie(mt.atan(2*np.pifRC) (180/(np.pi)))。我不知道为什么。

我已经尝试将 arange 更改为 linspace,但我仍然遇到同样的问题。

import matplotlib.pylab as plt
import numpy as np
import math as mt

R = 1000
C = 470*pow(10,-9)
f = np.arange(1,1000000)

kantelfrequentie = 1/(2*np.pi*R*C)
print("De kantelfrequentie is ",kantelfrequentie,"Hz")

Faseverschuiving = mt.atan(2*np.pi*R*C*kantelfrequentie)
print("De faseverschuiving bedraagt",Faseverschuiving,"rad")
#Omzetten radialen in graden
Faseverschuiving = Faseverschuiving * (180/(np.pi))
print("De faseverschuiving bedraagt",Faseverschuiving,"°")

faseverschuiving_functie = []

#Functie opstellen
faseverschuiving_functie(mt.atan(2*np.pi*f*R*C)* (180/(np.pi)))

#---------------------------------------------------------------------------
#Plot de eerste grafiek
#Grootte van de figuur en de subplot bepalen 
plt.figure(figsize=(10,10))
plt.subplot(111)
#Titel van de grafiek
plt.title("faseverschuiving = f(frequentie)")
#Grafiek plotten
plt.plot(f,faseverschuiving_functie,"r*-",label = "Faseverschuiving")
#Assen benoemen
plt.xlabel("f (Hz)")
plt.ylabel("φ (°)")
plt.grid()
plt.legend()

此代码的输出通常是图形,但 de faseverschuiving_functie 给我一个类型错误,我不知道为什么。 f(frequentie)和faseverschuiving_functie的长度是一样的。

【问题讨论】:

    标签: python typeerror


    【解决方案1】:

    那是因为math.atan 需要一个标量值,并且在它内部的某个地方,它会做出这样的断言。例如,如果您尝试调用math.atan([1,2]),它也会抛出一个TypeError,而2 * np.pi * f * R * C 会产生一个数组。

    faseverschuiving_functie 也存在问题,您之前在代码中将其定义为 faseverschuiving_functie = []。调用faseverschuiving_functie 会导致错误,因为faseverschuiving_functie 是一个列表而不是一个函数。

    【讨论】:

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