python - 使用log in numpy求解贷款偿还公式

标签 python numpy math

我正在求解http://financeformulas.net/Loan_Payment_Formula.html处的贷款偿还公式中的n

这个简化版本只有 1 个 n 值:

P = (r * PV) / (1 - (1 + r) ** -n)

P = payment
PV = present value
r = rate per period
n = number of periods

我相信我已经解决了n:

P = (r * PV) / (1 - (1 + r)**-n)

P * (1 - (1 + r)**-n) = (r * PV)

1 - (1 + r)**-n = (r * PV) / P

1  = (r * PV / P) + (1 + r) ** -n

1  - (r * PV / P) = (1 + r) ** -n

1  - (r * PV / P) = 1 /(1 + r) ** n

((1 + r) ** n) * (1  - (r * PV / P)) = 1

(1 + r) ** n = 1 / (1  - (r * PV / P))

n * log(1 + r) = log(1 / (1  - (r * PV / P))) 

n  = log(1 / (1  - (r * PV / P))) / log(1 + r) # finally done!

我的问题是将其转换为Python。当我在计算器上执行 log(3) 时,我得到 0.477

当我使用 numpy 时,我得到:

In [1]: import numpy

In [2]: numpy.log(3)
Out[2]: 1.0986122886681098

In [3]: numpy.log10(3)
Out[3]: 0.47712125471966244

因此,到目前为止,我使用 numpy 转换为 python 的假设是:

periods_of_time  = numpy.log10(1 / (1  - (r * PV / P))) / numpy.log10(1 + r)

本文展示了如何求解指数变量...您使用 log: http://mathonweb.com/help_ebook/html/expolog_4.htm

当我运行它时,我收到一个错误:

def get_periods_from_payment(present_value, rate_per_period, payment):
    rate_as_decimal = rate_per_period / 100
    return log10(1 / (1  - (rate_per_period * present_value / payment))) / log10(1 + rate_per_period)

# test get_interest_paid_from_periods()
result = get_interest_paid_from_periods(35000, 0.5, 180)
print(result)
assert result == 18163

错误是:

$ python interest_calculator.py 
295.35
interest_calculator.py:59: RuntimeWarning: invalid value encountered in log10
  return log10(1 / (1  - (rate_per_period * present_value / payment))) / log10(1 + rate_per_period)
nan
Traceback (most recent call last):
  File "interest_calculator.py", line 101, in <module>
    assert result == 180
AssertionError

一个类似的答案说这意味着指数中有负值,但如果我正确解决它应该可以工作。

最佳答案

计算器上的log以10为底,而Python中的loge为底。 由于您要将一个对数除以另一个相同底数的对数实际上并不重要您使用哪个底数作为对数。这是因为您隐式使用 base change rule计算以 1+r 为底的 1/(1 - (r * PV/P)) 的对数。

关于python - 使用log in numpy求解贷款偿还公式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45258872/

相关文章:

math - 在 Python 中编写简单数学计算的最佳实践

math - 将捕获的坐标转换为屏幕坐标

python - 使用字典映射将格式应用于 Dataframe 中的每一列

python - 从二维矩阵获取坐标列表

python - 残差图诊断以及如何改进回归模型

arrays - Numpy 连接很慢 : any alternative approach?

python - 如何衡量 Python 中最佳拟合线的质量?

ios - Scenekit Pan 2D Translation to Orthographic 3D only horizo​​ntal

python - 扩展第一个容器以输出额外的 div 属性

python - 按钮selenium python内div内元素span的唯一xpath