Python Cython:TypeError:需要整数
我使用Python2.7.8和Cython0.2.1运行Anaconda2.1.0。 我在文件中定义了Python Cython:TypeError:需要整数,python,cython,Python,Cython,我使用Python2.7.8和Cython0.2.1运行Anaconda2.1.0。 我在文件中定义了 def Implied_Vola(underlyingPrice,strikePrice,interestRate,daysToExpiration,price,optiontype): underlyingPrice = float(underlyingPrice) strikePrice = float(strikePrice) interestRate = fl
def Implied_Vola(underlyingPrice,strikePrice,interestRate,daysToExpiration,price,optiontype):
underlyingPrice = float(underlyingPrice)
strikePrice = float(strikePrice)
interestRate = float(interestRate) / 100
daysToExpiration = float(daysToExpiration) / 365
price = round(float(price), 6)
implied_Volatility = calc_implied_volatility(underlyingPrice,strikePrice,interestRate,daysToExpiration, price, optiontype)
return implied_Volatility
及
我得到“TypeError:需要一个整数。”当
implied_Volatility = calc_implied_volatility(underlyingPrice,strikePrice,interestRate,daysToExpiration, price, optiontype)
被称为
为什么呢?我找不到任何bug。这是
选项type
参数。奇怪的是,Cythonchar
类型需要一个整数。您应该将cython类型更改为str
或char*
,或者从python传递ord(字符串[0])
小例子:
# file: cdef.pyx
cpdef f(char c):
print c
然后,在python shell中:
>>> import pyximport; pyximport.install(); import cdef
>>> cdef.f('hello')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "cdef.pyx", line 1, in cdef.f (.../cdef.c:598)
cpdef f(char c):
TypeError: an integer is required
>>> cdef.f('h')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "cdef.pyx", line 1, in cdef.f (.../cdef.c:598)
cpdef f(char c):
TypeError: an integer is required
>>> cdef.f(5)
5
>>导入pyximport;pyximport.install();导入cdef
>>>cdef.f('hello')
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
文件“cdef.pyx”,第1行,在cdef.f(…/cdef.c:598)中
CPF(字符c):
TypeError:需要一个整数
>>>cdef.f('h')
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
文件“cdef.pyx”,第1行,在cdef.f(…/cdef.c:598)中
CPF(字符c):
TypeError:需要一个整数
>>>cdef.f(5)
5.
这里有一个类似的问题:我不会为optiontype
指定变量类型,但您可以在您的案例中使用str optiontype
。当您必须迭代数组或将数据传递给C函数时,指定类型会为您带来更多优势,在这种情况下,它会给代码带来不必要的复杂性。
# file: cdef.pyx
cpdef f(char c):
print c
>>> import pyximport; pyximport.install(); import cdef
>>> cdef.f('hello')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "cdef.pyx", line 1, in cdef.f (.../cdef.c:598)
cpdef f(char c):
TypeError: an integer is required
>>> cdef.f('h')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "cdef.pyx", line 1, in cdef.f (.../cdef.c:598)
cpdef f(char c):
TypeError: an integer is required
>>> cdef.f(5)
5