Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
So i have this task, i need to create formula in python, I have all the program running good, but i just can't think of the formula to count years, that's compound interest
what i need to count is how many years will it take to get to the target(lets say from 1500 to 2000)
Got this formula t = ln(A/P) / n[ln(1 + r/n)], but i don't get the right answer
https://www.thecalculatorsite.com/articles/finance/compound-interest-formula.php
Also tried this
https://www.algebra.com/algebra/homework/logarithm/logarithm.faq.question.117944.html
update.
Thanks for help! answer in comments for those who have same issue
This might work:
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.
EDIT: Adding solution for comment below:
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)
Compound Interest Calculator:
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) + "%.")
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 months ago.
Improve this question
from math import sin, cos
def Sling():
b_h = float(input("Input starting speed: "))
b_angl = float(input("Input starting angle: "))
vy = b_h * sin(b_angl)
vx = b_h * cos(b_angl)
g = 9.8
t = (vy/8)
Max_height = (vy - (-g*t*t)) # max height of the throw
tx = 0
Projectile_CS = (vy * tx) - (-g*tx*tx) # current spot of the projectile
while Projectile_CS >= 0:
tx += 0.1
else:
print("Done")
Max_distance = tx * vx
print("Max")
for x in range(round(float(Max_height)/5)):
print("*")
print("0", "_" * t, "_" * round((Max_distance)/5))
print("The maximum height is: ", round(Max_height))
print("Max distance is: ", round(Max_distance))
return
Sling()
After the while Projectile_CS >= 0: part of the code, it doesn't do anything, or looks like it. I can stop the code or restart with debugging but it doesn't help.
You never update Projectile_cs in the while loop, therefore you get stuck inside it
Your while loop continues until Projectile_speed value is < 0, but since you never change projectile_speed value in the while loop it will forever be < 0
For your code to work you have to update your variable in the while loop, according to what you did earlier it would probably look something like that
Projectile_CS = (vy * tx) - (-g*tx*tx)
while Projectile_CS >= 0:
tx += 0.1
Projectile_CS = (vy * tx) - (-g*tx*tx)
This program is meant to get input from the user, initial investment and apy and is meant to return the number of years it takes for the investment to double. I've been testing 100 for the principal and .05 for the apy but the result I'm getting is over 14,000 years. This value should calculate to a little over 15 years. I can seem to find the issue and could use some pointers.
def main():
print("This program calculates the amount of time it takes for an investment to double")
principal = eval(input("What is the initial investment amount? "))
apy = eval(input("What is the annual interest rate? "))
years = 0
while principal < (2 * principal):
principal = principal * (1 + apy)
years = years + 1
print("It will take", years, "years for your investment to double." )
main()
when you increase the pricipal in every loop you also increase 2 times principal
as x+1 < (x+1)* 2
And you have your infinite loop in at least theory
But python stops at ∞ < 2 * ∞ and that is correct as 2 * ∞ Is ∞ and makes the equation false and ends the loop
Add another variable.
def main():
print("This program calculates the amount of time it takes for an investment to double")
principal = eval(input("What is the initial investment amount? "))
apy = eval(input("What is the annual interest rate? "))
years = 0
resultinv = principal
while resultinv < (2 * principal):
resultinv = resultinv * (1 + apy)
years = years + 1
print("It will take", years, "years for your investment to double." )
main()
I’d like to know whether this is the formula problem or my problem.
I’ve looked up various formulas online. This is edx’s formula
Cost * Number of Months * Monthly Rate / 1 - ((1 + Monthly Rate) ** Number of Months)
cost = 150000
rate = 0.0415
years = 15
rate = rate / 12
years = years * 12
house_value = cost * years * rate
house_value2 = (1 + rate) ** years
house_value = house_value / house_value2
house_value = round(house_value, 2)
print("The total cost of the house will be $" + str(house_value))
It should print “The total cost of the house will be $201751.36” but it prints “The total cost of the house will be $50158.98”
Going off your answer with the correct formula, you can simplify the code quite a bit and add more readability by doing the following:
# This is a function that lets you calculate the real mortgage cost over
# and over again given different inputs.
def calculate_mortgage_cost(cost, rate, years):
# converts the yearly rate to a monthly rate
monthly_rate = rate / 12
# converts the years to months
months = years * 12
# creates the numerator to the equation
numerator = cost * months * monthly_rate
# creates the denominator to the equation
denominator = 1 - (1 + monthly_rate) ** -months
#returns the calculated amount
return numerator / denominator
# sets the calculated amount
house_value = calculate_mortgage_cost(150000, 0.0415, 15)
# This print statement utilizes f strings, which let you format the code
# directly in the print statement and make rounding and conversion
# unnecessary. You have the variable inside the curly braces {}, and then
# after the colon : the comma , adds the comma to the number and the .2f
# ensures only two places after the decimal get printed.
print(f"The total cost of the house will be ${house_value:,.2f}")
I have now solved this. This is the edit.
cost = 150000
rate = 0.0415
years = 15
house_value = cost * (years * 12) * (rate / 12)
house_value2 = 1 - (1 + (rate / 12)) ** -years
house_value = house_value / house_value2
house_value = round(house_value, 2)
print("The total cost of the house will be $" + str(house_value))
I have added a negative sign to the years.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I need some help, trying to print in the following format:
00: 0
01: 1
02: 1
03: 2
04: 3
05: 5
06: 8
07: 13
08: 21
09: 34
10: 55
My codes:
import math
import time
start_time = time.time()
golden_ratio = (1 + math.sqrt(5)) / 2
def main():
num = int(input("How many Fibonacci numbers should I print? "))
for number in range(0,num+1):
val = (golden_ratio**number - (1 - golden_ratio)**number) / math.sqrt(5)
print(format(round((val)),'3d'))
main()
def main():
stnum = input("How many Fibonacci numbers should I print? ")
dig = len(stnum)
num = int(stnum)
for number in range(0,num+1):
val = (golden_ratio**number - (1 - golden_ratio)**number) / math.sqrt(5)
#print(format(round((val)),'3d'))
print(f"{number:0{dig}d}: {val:.0f}")
dig is the number of digits of the amount of Fibonacci numbers: if you ask for 100 Fibonacci numbers, dig is 3. I use formatted string literals (available since python 3.6) to format the output.
{number:0{dig}d} prints the integer number with dig leading 0.
{val:.0f} prints a float with no digits after the dot.
If you have an older version of python and formatted string literals are not available, replace the print statement with this:
print("{}: {:.0f}".format(str(number).zfill(dig), val))
import math
import time
start_time = time.time()
golden_ratio = (1 + math.sqrt(5)) / 2
def main():
num = int(input("How many Fibonacci numbers should I print? "))
for number in range(0,num+1):
val = (golden_ratio**number - (1 - golden_ratio)**number) / math.sqrt(5)
print('{}: {:.0f}'.format(number, val))
main()
import math
import time
start_time = time.time()
golden_ratio = (1 + math.sqrt(5)) / 2
def main():
num = int(input("How many Fibonacci numbers should I print? "))
for number in range(0,num+1):
val = (golden_ratio**number - (1 - golden_ratio)**number) / math.sqrt(5)
print(format(number, '02d'), ': ', format(round((val)),'3d'))
main()
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
This is a very simple piece of code that I wrote but if there is a way to make it more pythonic then I would love to know. Thanks!
def money():
current_salary = float(input("What is your current salary? "))
years = int(input("How many years would you like to look ahead? ")) + 1
amount_of_raise = float(input("What is the average percentage raise you think you will get? "))
amount_of_raise = amount_of_raise * 0.01
while years > 1:
years = years - 1
new_salary = current_salary + (current_salary * amount_of_raise)
current_salary = new_salary
print('Looks like you will be making', new_salary,' in ', years,'years.')
money()
Extended assignment operators
amount_of_raise = amount_of_raise * 0.01
years = years - 1
x = x * y can be shortened to x *= y. Same thing for -.
amount_of_raise *= 0.01
years -= 1
Iteration and counting
while years > 1:
years = years - 1
Counting down causes your printouts to display backwards. I would count up. The Pythonic way to count uses range:
for year in range(1, years + 1):
print('Looks like you will be making', new_salary,' in ', years,'years.')
Computing new salary
new_salary = current_salary + (current_salary * amount_of_raise)
current_salary = new_salary
I'd probably just simplify that to:
current_salary += current_salary * amount_of_raise
Or even better is to give a 5% raise by multiplying by 1.05. In code that is:
current_salary *= 1 + amount_of_raise