I am attempting to write a function (in Python 2.7) which takes an outstanding balance and annual interest rate then returns the min monthly payment to the nearest cent using bisection search to solve problem #3. I am trying to follow DRY principles by writing a function inside the main function which should return a list with the balance after a year and the number of months (the loop should break if balance hits zero or less) which will need to be calculated twice in my main function. As I try to test this initial closure before moving on I am getting a syntax error on the line assigning monthlyPayment. What am I doing wrong?
# Problem Set 1("C")
# Time Spent: xx hours
def payInOne_BisectionSearch (balance,annualRate):
#initialize variables
initialBalance = balance
monthlyRate = annualRate/12
minMonthly = balance/12
maxMonthly = (balance * (1 + monthlyRate ** 12 )/12
monthlyPayment = (minMonthly + maxMonthly)/2
numMonths = 1
#define function to check balance after 12 months
def balanceAfterYear (balance, monthlyRate, monthlyPayment):
for numMonths in range (1,13):
interest = balance * monthlyRate
balance += interest - monthlyPayment
if balance <= 0:
break
return [balance, numMonths]
resultList = balanceAfterYear(initialBalance, monthlyRate, monthlyPayment)
print resultList[0],resultList[1]
payInOne_BisectionSearch (input("Enter the outstanding balance"),input("Enter annual rate as a decimal"))
You forgot a closing bracket in the previous line.
maxMonthly = (balance * (1 + monthlyRate ** 12 )/12
Related
I started working on a problem in the past several days...
A company plans its business in a three month period. It can produce
110 units at a cost of 600 each. The minimum amount it must produce
per month is 15 units if active (but of course, it can choose to be closed
during the month, and produce 0 units). Each month it can subcotract the
prodution of 60 units, at a cost of 660 each. Storing a unit for one month
costs 20$ per unit per month. The marketing department has forcasted
sales of 100, 130 and 150 units for the next three months, respectively.
The goal is to meet the demand each month while minimizing the total
cost.
I deduced that we need to have an objective function of form min[Sum(i=0..3) 600*x1+660*x2+20*x3].
We need to add some constrains on x1>=15, and on x2 0<=x2<=60
Also we will also need another constraint for each month...
For the first one i=1 => x1+x2 = 100 - x3last (x3last is an extra variable that should hold the amount existing in deposit from the previous month), and for i=2 and i=3 same constraints.
I don't have any idea how to write this in pulp, and i would appreciate some help. Thx ^_^
I'd tend to agree with #Erwin that you should focus on formulating the problem as a Linear Program. It is then easy to translate this into code in PULP or one of many other PULP libraries/tools/languages.
As an example of this - lets work through this process for the example problem you have written out in your question.
Decision Variables
The first thing to decide is what you can/should decide. This set of information is called the decision variables. Picking the best/easiest decision variables for your problem comes with practice - the important thing is that once you know the values of the variables you have a unique solution to the problem.
Here I would suggest the following. These assume that the forecasts for demand are perfect. For each month i:
Whether the production line should be open - o[i]
How much to produce in that month - p[i]
How much to hold in storage for next month - s[i]
How much to get made externally - e[i]
Objective Function
The objective in your case is obvious - minimise the total cost. So we can just write this down: sum(i=0...2)[p[i]*600 + s[i]*20 + e[i]*660]
Constraints
Let's lift these directly our of your problem description:
"It can produce 110 units at a cost of 600 each. The minimum amount it must produce per month is 15 units if active (but of course, it can choose to be closed during the month, and produce 0 units)."
p[i] >= o[i]*15
p[i] <= o[i]*110
The first constraint forces the minimum production about to be 15 if the production is open that month (o[i] == 1), if the production is not open this constraint has not effect. The second constraint sets a maximum value on p[i] of 110 if the production is open and a maximum production of 0 if the production is closed that month (o[i] == 0).
"Each month it can subcotract the prodution of 60 units, at a cost of 660 each"
e[i] <= 60
"The marketing department has forcasted sales of 100, 130 and 150 units for the next three months, respectively. The goal is to meet the demand each month while minimizing the total cost." If we declare the sales in each mongth to be sales[i], we can define our "flow constraint" as:
p[i] + e[i] + s[i-1] == s[i] + sales[i]
The way to think of this constraint is inputs on the left, and outputs on the right. Inputs of units are production, external production, and stuff taken out of storage from last month. Outputs are units left/put in storage for next month and sales.
Finally in code:
from pulp import *
all_i = [1,2,3]
all_i_with_0 = [0,1,2,3]
sales = {1:100, 2:130, 3:150}
o = LpVariable.dicts('open', all_i, cat='Binary')
p =LpVariable.dicts('production', all_i, cat='Linear')
s =LpVariable.dicts('stored', all_i_with_0, lowBound=0, cat='Linear')
e =LpVariable.dicts('external', all_i, lowBound=0, cat='Linear')
prob = LpProblem("MinCost", LpMinimize)
prob += lpSum([p[i]*600 + s[i]*20 + e[i]*660 for i in all_i]) # Objective
for i in all_i:
prob += p[i] >= o[i]*15
prob += p[i] <= o[i]*110
prob += e[i] <= 60
prob += p[i] + e[i] + s[i-1] == sales[i] + s[i]
prob += s[0] == 0 # No stock inherited from previous monts
prob.solve()
# The status of the solution
print ("Status:", LpStatus [prob.status])
# Dislay the optimums of each var
for v in prob.variables ():
print (v.name, "=", v.varValue)
# Objective fcn
print ("Obj. Fcn: ", value(prob.objective))
Which returns:
Status: Optimal
external_1 = 0.0
external_2 = 10.0
external_3 = 40.0
open_1 = 1.0
open_2 = 1.0
open_3 = 1.0
production_1 = 110.0
production_2 = 110.0
production_3 = 110.0
stored_0 = 0.0
stored_1 = 10.0
stored_2 = 0.0
stored_3 = 0.0
Obj. Fcn: 231200.0
I am studying SAS on my own. I have no one to refer to so I just wanted to check if my code is correct.
In a fixed term deposit of 25 years calculate the total amount at the end of
term with initial amount of $5,00,000 and annual interest rate of 7 % */
1) Compounded Annually
2) Compounded Monthly.Show the amount at monthly level
My Code:
data deposit;
amount = 500000;
rate = 0.07;
do year = 1 to 25;
amount + earned;
earned + (amount*0.07);
principal = amount + earned;
output;
end;
run;
For the second question compounded monthly
data deposit1;
rate = 0.006;
amount1 = 500000;
do year = 1 to 25;
do month = 1 to 12;
earned1 + (earned1 + amount1)*0.006;
amount1 + earned1;
output;
end;
end;
run;
Pasting the Screenshots of Solution 1 and Solution 2
I am confused because when I compound annually and monthly both have different results at the end of a particular year.
Please suggest if anything is wrong in my code. Thank you for your time and attention.
It looks like you are double-counting your earned1 variable in the monthly compounding code.
earned1 + (earned1 + amount1)*0.006;
amount1 + earned1;
Should be:
earned1 = amount1*0.07**(1/12);
amount1 + earned1;
Note also you will not want to round the interest rate.
I'm looking at figuring out this program for a lab, I have been working on it for a while now, but cannot for the life of me figure out how this works.
The objective is to display an active equation as it decrements from from the initial value.
For example:
20000.00 + 83.33 - 150.00 = 19933.33
19933.33 + 83.06 - 150.00 = 19866.39
19866.39 + 82.78 - 150.00 = 19799.17
19799.17 + 82.50 - 150.00 = 19731.66
19731.66 + 82.22 - 150.00 = 19663.88
19663.88 + 81.93 - 150.00 = 19595.81
19595.81 + 81.65 - 150.00 = 19527.46
And so forth. I have to display that as an output on the screen. But am not sure how to keep a decrementing total like that and how to display it as an active equation like that in cout form.
The number on the far left is an initial loan that a user inputs, the number in the middle is the interest rate which is calculate using p*r/p (initial loan * interestrate(user will input this as well)/ initial loan). And the number on the right just before the equal sign is a payment which the usual will enter.
The goal is to get it to perform 10 iterations or once the initial loan is fully paid off whichever comes first.
Here is a little guidance
Finance
First you got your basics wrong. If this is finance and it looks this way :-), p*r/p is crap.
The second column in your plot is not a rate, neither is it an interest rate, it is an interest.
P is the loan ammount
r is an annual interest rate
The interest is calculated using P times r/12 since the payments you show are monthly in case r is entered mathematically (e.g. 0.05 for 5 %) or P*r/1200 in case r is counterconventional entered as percentage.
C++
The input of the parameters could be done e.g.
double P, r, q;
std::cout << "Enter P, q and r:\t";
std::cin >> P >> r >> q;
you will need to have the numbers printed fixed precision, this can by done with
std::cout << std::fixed << std::setprecision(2)
one last hint: The needed include files will be
#include <iostream>
#include <iomanip>
last you will need a loop have a look for for-loops or do-while loops.
This should help you to get your homework a good start.
minimunpaymonth = 0
balance = 4773
annualInterestRate = 0.2
def function(minimunpaymonth):
global balance
month = 1
while month <= 12:
balance = balance - minimunpaymonth
anninterest = annualInterestRate/12 * balance
balance = balance + anninterest
month += 1
return balance
while function(minimunpaymonth) >= 0:
minimunpaymonth += 10
print "Lowest Payment: " + str(minimunpaymonth)
the second while loop is infinite and i dont know why. the first is ok because i have ran it
when the loop increases minimunpaymonth, value of balance goes down, so there will be a moment when balance is negative
def function(minimunpaymonth, balance, annualInterestRate):
month = 1
while month <= 12:
balance = balance - minimunpaymonth
anninterest = annualInterestRate/12 * balance
balance = balance + anninterest
month += 1
return balance
while function(minimunpaymonth, balance, annualInterestRate) >= 0:
minimunpaymonth += 10
print "Lowest Payment: " + str(minimunpaymonth)
ok i just solved it. i change the function to give 3 arguments instead of 1
your second loop is checking to see if minimunpaymonth is >= 0, if it is then it performs the loop again.
Your minimunpaymonth will always be >=0 because it starts at 0 & is only ever added to. There is no subtraction from this value.
the second loop keeps adding to minimum payment, it will always be >= 0 till it reaches the numeric limit of the variable; however as the comment pointed out, the "function" could get less, but perhaps the interest rate always keeps the balance above zero and the minimum payments don't get it there -- plausible enough in real life!
Assume you are given three variables, revenue, expenses, and profit, all of type Money (a structured type with two int fields, dollars and cents). Assign to profit the result of subtracting expenses from revenue. Let's make the happy assumption that revenue exceeds expenses. However you still may find that the cents part of expenses exceeds that of revenue. If that is the case you will have to "borrow" 1 from revenue dollars (i.e. subtract 1) and "give" it to revenue's cents (i.e. add 100!) in order to carry out the subtraction properly.
Here is what I have but it's not working:
if (revenue.cents < expenses.cents)
{
revenue.dollars = revenue.dollars -1;
revenue.cents = revenue.cents + 100;
profit = revenue - expenses;
}
else
{
profit = revenue - expenses;
}
I get this error message:
error: no match for 'operator-' in 'revenue - expenses'
Any help is appreciated. Thanks.
You're getting that error because you cannot subtract one structure from another. You will have to define an operator-() function for your struct.
You need to call each element of the structure and subtract them separately. MyProgLab will not allow you to define a function for this exercise. Not only that but if you enter the code that you have above it will tell you that 'you were not supposed to modify the element'. In order to avoid this you must conduct the borrowing of the dollar inside the arithmetic.
Like this:
if(expenses.cents > revenue.cents)
{
profit.dollars = (revenue.dollars - 1) - expenses.dollars;
profit.cents = (revenue.cents + 100) - expenses.cents;
}//end if