计算年复利python

时间:2020-10-19 02:39:02

标签: python python-3.x

所以我有这个任务,我需要在python中创建公式,我所有的程序都运行良好,但是我只是想不出要计算年份的公式,这就是复利

我需要数的是到达目标需要多少年(比如说从1500年到2000年)

得到这个公式t = ln(A / P)/ n [ln(1 + r / n)],但是我没有得到正确的答案 https://www.thecalculatorsite.com/articles/finance/compound-interest-formula.php

也尝试过 https://www.algebra.com/algebra/homework/logarithm/logarithm.faq.question.117944.html

更新。 感谢帮助!回答有同样问题的人

2 个答案:

答案 0 :(得分:0)

复合利息计算器:

import math

P = float(input("Enter the initial deposit: "))
A = float(input("Enter the final amount: "))
N = float(input("Enter the number of times the interest is applied per time period: "))
T = float(input("Enter the number of time periods elapsed: "))

interestRate = N*(pow(A/P, 1/(N*T))-1)*100
print("The interest rate is " + str(interestRate) + "%.")

答案 1 :(得分:0)

这可能有效:

from math import log

p_start = 1500 # Beginning principal
r = 4.3 # Interest rate
p_end = 2000 # Ending principal

"""
# Lambda function
# n == number of compounding periods per year.
    # Default n is 12, or monthly compounding

# Formula Breakdown
round((
       log(A / P) /
       (n * (
               log(1 + (r/n))
               )
        )
    # Add 0.5 to account for needing to round up.
    ) + 0.5
# Round to zero decimal places
, 0)
"""
get_time = lambda A, P, r, n=12: round((log(A / P) / (n * (log(1 + (r/n))))) + 0.5, 0)

# If interest rate isn't a percentage, convert it
if r > 0:
    r /= 100

get_time(p_end, p_start, r, 1) # 7.0 using n = 1, or compounded once per year.

编辑:在下面添加评论解决方案:

def calculate_years_to_target(principal, rate, target, n=12):

    if rate > 0:
        rate /= 100

    years = round((math.log(target / principal) / (n * (math.log(1 + (rate/n))))) + 0.5, 0)
    return years


calculate_years_to_target(1500, 4.3, 2000, 1)