2017-04-09 65 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

相關問題