How to apply recursion to an algorithm? - python

I am trying to write a predator-prey model where I take the input for the amount of rabbits, foxes, and years. Then output the final number of rabbits and foxes after that amount of years. I am able to return an amount of rabbits and foxes, but I am not getting the correct values. The algorithm for the foxes and rabbits after one year are:
F1yr = F0yr – Floor(F0yr * (G-S * R0yr))
R1yr = R0yr + Floor( R0yr * (A-B * F0yr))
Where A = 0.04, B = 0.0005, G = 0.2, and S=0.00005
For a starting input of 5891 rabbits and 16 foxes after 99 years, it should return 6484 rabbits and 144 foxes, but I am getting 4682 rabbits and 189 foxes.
This is the code that I have so far, I feel like I am close to the answer, but not fully there:
def bunnies(rabbits,foxes,years):
if __name__ == '__main__':
if years == 0:
tot = []
tot.append(rabbits)
tot.append(foxes)
return tot
else:
a = 0.04
b = 0.0005
g = 0.2
s = 0.00005
rabbits = rabbits + math.floor(rabbits * (a-b * foxes))
foxes = foxes - math.floor(foxes * (g-s * rabbits))
return bunnies(rabbits,foxes,years-1)
rabbits = int(input('Enter Initial Rabbit Population:\n'))
foxes = int(input('Enter Initial Fox Population:\n'))
years = int(input('Enter Number of Years to Simulate:\n'))
print(bunnies(rabbits,foxes,years))

Your code was almost correct, here is a fixed and cleaned up version:
import math
def bunnies(rabbits, foxes, years):
A = 0.04
B = 0.0005
G = 0.2
S = 0.00005
if years == 0:
return rabbits, foxes
else:
rabbits_last, foxes_last = rabbits, foxes
foxes = foxes_last - math.floor(foxes_last * (G - S * rabbits_last))
rabbits = rabbits_last + math.floor(rabbits_last * (A - B * foxes_last))
return bunnies(rabbits, foxes, years - 1)
if __name__ == '__main__':
rabbits = int(input('Enter Initial Rabbit Population: '))
foxes = int(input('Enter Initial Fox Population: '))
years = int(input('Enter Number of Years to Simulate: '))
print(bunnies(rabbits, foxes, years))
The problem ocurred when you used the already changed value of the rabbit population for the new fox population count.
You also used wrong variable names when calling print(bunnies(rab,fox,yrs)), but I think that was just a copying mistake since you didn't get error messages.
Lastly your if __name__ == '__main__' shouldn't have been inside the function but on the module scope like I have it.

Related

Wrong calculation in Python for overpayment

I started an online training for Python. The assignment wants to me calculate 45 hours work for 10.50 hourly payment. But, 5 hours in this is overwork. So, the payment goes to 10.50 X 5
So, the payment should be 498.75.
But, my program finds different sum. What is wrong with this code? (Note that I am novice)
hours = float(input("Enter hours: "))
rate = float(input("Enter rate: "))
extraPay = float((hours-40) * (rate*1.5))
def computepay(a, b, c):
paymentCalc= a * b + c
return paymentCalc
x = computepay(hours, rate, extraPay)
print(x)
you need to substract extra hours from basic hours on calculations and also add check that extra_pay will not be in negative. Do, Like this:
hours = float(45)
rate = float(10.5)
extra_hours = float(hours - 40)
extraPay = float(extra_hours * (rate*1.5))
def computepay(a, b, c, d):
if c < 0:
c = 0
payment_calc = (a - d) * b + c
return payment_calc
x = computepay(hours, rate, extraPay, extra_hours)
print(x)
The problem is that you are adding the overpay hours twice, once with the increased rate in extraPay and once in your payment calc (a is still 45).
Also, you need to check if hours are less than 40 because if it is less, extraPay will be negative and your calculation will be wrong.
Here is my suggestion:
def computepay(hours, rate):
bonus = 0
if hours>40:
overtime = hours-40
hours=40
bonus = (overtime)*rate*1.5
return hours*rate+bonus
Try:
hours = float(input("Enter hours: "))
rate = float(input("Enter rate: "))
remainder=(max(0,hours-40))
def computepay(a, b):
paymentCalc= a * b
return paymentCalc
def compute_ext(remainder,rate):
ext = remainder * (rate*1.5)
return ext
base = computepay(min(40,hours), rate)
if remainder:
base+=compute_ext(remainder,rate)
print(base)
you used all the hours instead for a max of 40 to calculate the base pay

calculate years compound interest python [closed]

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) + "%.")

CS1301xl Computing in Python I practice exam mortgage problem’s formula may be somehow incorrect?

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.

Compound interest with deposits in Python

I am working on an assignment for a comp sci class. I feel like I am really close but I cant quite get to the answer. Basically the assignment is a compound interest calculator, what I am trying to do that makes it more complicated is adding deposits to the initial investment and allowing for someone to stop paying into it at one point, but collect it at a different point. The example is ", a user may already have
saved $10,000 in their account when they start their retirement calculation. They intend to save
another $1000 per year for the next 10 years at which point they will stop making any additional
deposits into their account. However, they may be 20 years away from retirement. Your program
should be able to account for these varying inputs and calculate the correct future value of their
account at retirement"
Here is my code so far:
def main():
print("Welcome to Letmeretire.com's financial retirement calculator!")
import random
num = random.randrange(10000)
principal = int(input("How much are you starting with for your retirement savings?"))
deposit = int(input("How much money do you plan to deposit each year?"))
interest = int(input("How much interest will your account accrue annually"))
time = int(input("Please enter the number of years that you plan to deposit money for."))
time_till_retirement = int(input("How long until you plan on retiring? (Please enter this amount in years)"))
t = time + 1
APR = interest/100
R = ((1+APR/12)**12)-1
DR = deposit/R
DRT = deposit/(R*(1+R)**time)
PV = principal+(DR-DRT)
future_value = PV*((1+APR/12)**12*time)
if time < time_till_retirement:
time1 = (time_till_retirement-time)
future = future_value*((1+APR/12)**12*time1)
else:
future = future_value
for i in range(1, t):
print("After " + str(i) + " years you will have "+ str(future) + " saved!")
main()
I would like the output to look like this:
Enter annual deposit: 1000
Enter interest rate: 12
Enter number of years until retirement: 10
What's the current balance of your account: 5000
How many years will you make your annual deposit? 5
After 1 year, you have: $ 6720.0
After 2 years, you have: $ 8646.4
After 3 years, you have: $ 10803.97
After 4 years, you have: $ 13220.44
After 5 years, you have: $ 15926.9
After 6 years, you have: $ 17838.13
After 7 years, you have: $ 19978.7
After 8 years, you have: $ 22376.14
After 9 years, you have: $ 25061.28
After 10 years, you have: $ 28068.64
But what Im getting is this:
Welcome to Letmeretire.com's financial retirement calculator!
How much are you starting with for your retirement savings?5000
How much money do you plan to deposit each year?1000
How much interest will your account accrue annually12
Please enter the number of years that you plan to deposit money for.5
How long until you plan on retiring? (Please enter this amount in years)10
After 1 years you will have 271235.9643776919 saved!
After 2 years you will have 271235.9643776919 saved!
After 3 years you will have 271235.9643776919 saved!
After 4 years you will have 271235.9643776919 saved!
After 5 years you will have 271235.9643776919 saved!
I think you need to ensure the formula is correct:
FV(t) = 5000 * (1.12 ** t) + 1000 * (1.12 ** t) + 1000 * (1.12 **
(t-1)) + ... + 1000 * 1.12
= 5000 * (1.12 ** t) + 1000 * (1.12 ** t - 1) * 1.12 / 0.12
Then we can define a function:
def fv(t, initial, annual, interest_rate):
return initial * (1+interest_rate) ** t + \
annual * (1+interest_rate) * ((1+interest_rate) ** t - 1) / interest_rate
Test:
print fv(1, 5000, 1000, 0.12)
print fv(3, 5000, 1000, 0.12)
print fv(5, 5000, 1000, 0.12)
Yields:
6720.0
10803.968
15926.8974592
Till now the main work is done, I think you can handle the rest.
In most cases, I would prefer Ray's analytic solution - plug the values into a formula, get the final answer, instead of iterating year by year.
However, in this case, you want the values for each year, so you may as well iterate after all:
import sys
# Python 2/3 compatibility shim
if sys.hexversion < 0x3000000:
rng = xrange
inp = raw_input
else:
rng = range
inp = input
def getter_fn(datatype):
if datatype == str:
return inp
else:
def fn(prompt=''):
while True:
try:
return datatype(inp(prompt))
except ValueError:
pass
return fn
get_float = getter_fn(float)
get_int = getter_fn(int)
def main():
print("Welcome to Letmeretire.com's financial retirement calculator!")
principal = get_float("Initial investment amount? ")
periods = get_int ("How many years will you make an annual deposit? ")
deposit = get_float("Annual deposit amount? ")
apr = get_float("Annual interest rate (in percent)? ") / 100
retirement = get_int ("Years until retirement? ")
deposits = [deposit] * periods
no_deposits = [0.] * (retirement - periods)
amount = principal
for yr, d in enumerate(deposits + no_deposits, 1):
amount = (amount + d) * (1. + apr)
print('After {:>2d} year{} you have: $ {:>10.2f}'.format(yr, 's,' if yr > 1 else ', ', amount))
if __name__ == '__main__':
main()
which results in
Welcome to the Letmeretire.com financial retirement calculator!
Initial investment amount? 5000
How many years will you make an annual deposit? 5
Annual deposit amount? 1000
Annual interest rate (in percent)? 12
Years until retirement? 10
After 1 year, you have: $ 6720.00
After 2 years, you have: $ 8646.40
After 3 years, you have: $ 10803.97
After 4 years, you have: $ 13220.44
After 5 years, you have: $ 15926.90
After 6 years, you have: $ 17838.13
After 7 years, you have: $ 19978.70
After 8 years, you have: $ 22376.14
After 9 years, you have: $ 25061.28
After 10 years, you have: $ 28068.64
FV(t) = 5000 * (1.12 ** t) + 1000 * (1.12 ** t) + 1000 * (1.12 ** (t-1)) + ... + 1000 * 1.12 = 5000 * (1.12 ** t) + 1000 * (1.12 ** t - 1) * 1.12 / 0.12
I have a similar problem like the one mentioned above but I do not get why the second part of the equation(formula) after the second equal sign?
Also is there not another way of doing this more concise without having to code "FV(t) = 5000 * (1.12 ** t) + 1000 * (1.12 ** t) + 1000 * (1.12 ** (t-1))" this part several times?

Loop not iterating

I'm running into a dilemma with a for i in range(x) loop not iterating. The purpose of my program is to simulate foxes and rabbits interacting with one another on an island and printing out the populations of each respective animal after each day. I know the equations are correct, the problem I am having is my loop will only run once for a large range.
My code:
def run_simulation():
print()
RABBIT_BIRTH_RATE = 0.01
FOX_BIRTH_RATE = 0.005
INTERACT = 0.00001
SUCCESS = 0.01
x = 0
y = 1
FOXES = eval(input("Enter the initial number of foxes: "))
print()
RABBITS = eval(input("Enter the initial number of rabbit: "))
print()
DAYS = eval(input("Enter the number of days to run the simulation: "))
print()
print("Day\t","Rabbits\t","Foxes\t")
print(0,"\t",RABBITS,"\t","\t",FOXES,"\t")
for i in range(DAYS):
RABBITS_START = round((RABBIT_BIRTH_RATE * RABBITS) - (INTERACT * RABBITS * FOXES))
FOXES_START = round((INTERACT * SUCCESS * RABBITS * FOXES) - (FOX_BIRTH_RATE * FOXES))
y = y + x
print (y,"\t",(RABBITS_START+RABBITS),"\t","\t",(FOXES_START+FOXES),"\t")
run_simulation()
When this is run with an example of 500 Foxes, 10000 Rabbits, and 1200 days, my output will look like
Day Rabbits Foxes
0 10000 500
1 10050 498
With the second output line repeating the remaining 1199 times.
Any help would be greatly appreciated I cannot figure out what I am doing wrong.
You set RABBITS and RABBIT_BIRTH_RATE at the beginning. Then, on every loop iteration, you set RABBITS_START to some formula involving these two numbers. You never change the value of RABBITS or RABBIT_BIRTH_RATE or FOXES or anything, so every time you run through the loop, you're just calculating the same thing again with the same numbers. You need to update the values of your variables on each iteration --- that is, set a new value for RABBITS, FOXES, etc.
The biggest issue for me is what you named your "change in rabbits/foxes". RABBITS_START sounds like an initial count for RABBITS, but it's not. This is why I renamed it to RABBITS_DELTA, because really it's calculating the CHANGE in rabbits for each day.
I think I got it. At the very least this behaves more like a simulation now:
def run_simulation():
RABBIT_BIRTH_RATE = 0.01
FOX_BIRTH_RATE = 0.005
INTERACT = 0.00001
SUCCESS = 0.01
x = 0
y = 1
FOXES = eval(str(input("Enter the initial number of foxes: ")))
RABBITS = eval(str(input("Enter the initial number of rabbits: ")))
DAYS = eval(str(input("Enter the number of days to run the simulation: ")))
print("Day\t","Rabbits\t","Foxes\t")
print(0,"\t",RABBITS,"\t","\t",FOXES,"\t")
count = 0
while count < DAYS:
RABBITS_DELTA = round((RABBIT_BIRTH_RATE * RABBITS) \
- (INTERACT * RABBITS * FOXES))
FOXES_DELTA = round((INTERACT * SUCCESS * RABBITS * FOXES) \
- (FOX_BIRTH_RATE * FOXES))
y = y + x
RABBITS += RABBITS_DELTA
FOXES += FOXES_DELTA
print (y,"\t",(RABBITS),"\t","\t",(FOXES),"\t")
count += 1
run_simulation()
I'm going to take a wild stab at trying to interpret what you mean:
for i in range(1, DAYS + 1):
rabbit_delta = ... # RABBITS_START
fox_delta = ... # FOXES_START
RABBITS += rabbit_delta
FOXES += fox_delta
print(i, "\t", RABBITS, "\t\t", FOXES, "\t")
edited based on others' answers. (Wild stab is less wild.)
See BrenBarn's answer for an explanation in prose.

Categories

Resources