Ipython 隐式类型错误:';十进制。十进制';对象不能解释为整数
我很难理解为什么Jupyter笔记本中的此功能显然失败了,但IPython外壳中却没有:Ipython 隐式类型错误:';十进制。十进制';对象不能解释为整数,ipython,decimal,jupyter-notebook,finance,computational-finance,Ipython,Decimal,Jupyter Notebook,Finance,Computational Finance,我很难理解为什么Jupyter笔记本中的此功能显然失败了,但IPython外壳中却没有: def present_value( r, n, fv = None, pmt = None ): ''' Function to compute the Present Value based on interest rate and a given future value. Arguments accepted ------------------
def present_value( r, n, fv = None, pmt = None ):
'''
Function to compute the Present Value based on interest rate and
a given future value.
Arguments accepted
------------------
* r = interest rate,
which should be given in its original percentage, eg.
5% instead of 0.05
* n = number of periods for which the cash flow,
either as annuity or single flow from one present value
* fv = future value in dollars,
if problem is annuity based, leave this empty
* pmt = each annuity payment in dollars,
if problem is single cash flow based, leave this empty
'''
original_args = [r, n, fv, pmt]
dec_args = [Decimal( arg ) if arg != None
else arg
for arg in original_args
]
if dec_args[3] == None:
return dec_args[2] / ( ( 1 + ( dec_args[0] / 100 ) )**dec_args[1] )
elif dec_args[2] == None:
# annuity_length = range( 1, dec_args[1] + 1 )
# Not allowed to add a Decimal object
# with an integer and to use it
# in the range() function,
# so we dereference the integer from original_args
annuity_length = range( 1, original_args[1] + 1 )
# Apply discounting to each annuity payment made
# according to number of years left till end
all_compounded_pmt = [dec_args[3] * ( 1 / ( ( 1 + dec_args[0] / 100 ) ** time_left ) ) \
for time_left in annuity_length
]
return sum( all_compounded_pmt )
当我使用functions import*中的,导入该函数所在的模块,名为functions.py
,然后执行present\u value(r=7,n=35,pmt=11000)
,我得到了错误:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-93-c1cc587f7e27> in <module>()
----> 1 present_value(r=7, n=35, pmt = 11000)
/path_to_file/functions.py in present_value(r, n, fv, pmt)
73 if dec_args[3] == None:
74 return dec_args[2]/((1 + (dec_args[0]/100))**dec_args[1])
---> 75
76 elif dec_args[2] == None:
77 # annuity_length = range(1, dec_args[1]+1)
TypeError: 'decimal.Decimal' object cannot be interpreted as an integer
有谁能帮我解决这个令人费解且晦涩难懂的问题吗?IIRC你是通过重启内核解决的吗?是的,我在IPython Github上发布这篇文章时,得到了帮助我的人的大力帮助:插入imp.reload()吗
进入IPython笔记本或类似的帮助允许我不重新启动内核吗?什么是好的做法?这要看情况而定。它甚至可能取决于您的Python版本。模块不应该是可重新加载的,但对于大多数模块来说,它是可以工作的。这就是Python的“我们在成年人之间”哲学。如果您想发疯并尝试imp.reload(),它可能会起作用,如果不起作用,那么它就不是一个真正的bug。
In [42]: functions.present_value(r=7, n=35, pmt = 11000)
Out[42]: Decimal('142424.39530474029537')