2017-04-09 64 views
1

这是我的代码经过由一系列函数生成一些浮点值到绘图仪:蟒3.4类型错误:坏的操作数类型为一元+:“发生器”

import numpy as np 
import matplotlib.pyplot as plt 

gK_inf = 20.70 
gK_0 = 0.01 
tauN = 0.915 + 0.037 

def graph(formula, t_range): 
    t = np.array(t_range) 
    gK = formula(t) # <- note now we're calling the function 'formula' with x 
    plt.plot(t, gK) 
    plt.xlabel(r"$g_K$") 
    plt.ylabel(r"$\frac{P_{i}}{P_{o}}$") 
    plt.legend([r"$\frac{P_{i}}{P_{o}}$"]) 
    annotation_string = r"$E=0$" 
    plt.text(0.97,0.8, annotation_string, bbox=dict(facecolor='red', alpha=0.5), 
     transform=plt.gca().transAxes, va = "top", ha="right") 
    plt.show() 

def my_formula(t): 
    return np.power((np.power(gK_inf,0.25))*((np.power(gK_inf,0.25)-np.power(gK_0,0.25))*np.exp(-t/tauN)),4) 

def frange(x, y, jump): 
    while x < y: 
     yield x 
     x += jump 

graph(my_formula, frange(0,11e-3,1e-3)) 

这是抛出的错误:

> gK = formula(t) # <- note now we're calling the function 'formula' 
> with x 
>  File "F:\Eclipse\my_test\gK", line 26, in my_formula 
>   return np.power((np.power(gK_inf,0.25))*((np.power(gK_inf,0.25)-np.power(gK_0,0.25))*np.exp(-t/tauN)),4) 
>  TypeError: bad operand type for unary -: 'generator' 

也希望你们,好吗?

+0

如果你想要一个浮点范围,可以使用'numpy.arange'或者''numpy.linspace'](https://docs.scipy.org/doc/numpy/reference/generated/numpy.linspace.html #numpy.linspace) –

回答

3

t_range是发电机。你试图用t = np.array(t_range)将它转换成一个numpy数组。但它不起作用。在生成器上调用np.array仅返回一个元素数组,其中只有生成器作为其唯一元素。它不会展开生成器。

你可以试试np.fromiter(t_range, dtype=np.float)代替。或者先将t_range转换成列表。

顺便提一下,目前还不清楚为什么你写了frange,因为它基本上是做内建range已经与其step论点。

+0

我照你说的:使用'np.fromiter(t_range)',现在我有这样的错误:'类型错误:必需的参数 'D型'(位置2)不found' – Roboticist

相关问题