I have no idea what is wrong in there:
current_pop = 7370000000
print "So the current population is", str(current_pop)
doubled_pop = 14740000000
year_1 = 2
year = 0
while current_pop != doubled_pop:
if current_pop != doubled_pop:
current_pop = current_pop * 2
year += 1
else:
year += 0
print year
I have already tried to like times that current pop by the year_1. But it keeps giving me year = 1
The problem in your program is that you assume that the population doubles every year! So of course under those conditions the population will double in exactly one year. Thankfully, our situation is not so dire. According to data provided by the World Bank, the annual rate of world population growth was 1.182% in 2015.
Your loop was unnecessarily complicated, but more importantly, your test was wrong. You (and a previous answer) had:
while current_pop != doubled_pop:
But this test will usually fail, since it is unlikely that the population will grow at a rate that conveniently lands on double the initial population on an exact year division. You need to use an inequality:
while current_pop < doubled_pop:
Here is a program that works:
current_pop = 7370000000
growth_rate = 0.01182
print "So the current population is", str(current_pop)
doubled_pop = 2 * current_pop
year = 0
while current_pop < doubled_pop:
current_pop = current_pop + (current_pop * growth_rate)
year += 1
print year
And here is the output:
So the current population is 7370000000
59
Related
I want to create a program to tell if a year is a leap or not
I have:
year = int(input("What year?: ")
year_div_4 = year / 4
Now the first step is:
if year_div_4 = float then the year is a leap... then year/100 and year/400 and so
But if i want to use the if statement:
if year_div_4 == ______:
What should I put in the blank space, because if the answer is a float then it is a leap, but if i put float in there then I get a float = 'undefined error'
Because python thinks i want to set year_div_4 equal to a variable
Better use the %-operator (modulo) e.g.:
if (year % 4 == 0):
print(f"{year} is divisible by 4")
Here is a complete example for leap year:
year = int(input("What year?: "))
if ((year % 400 == 0) or ((year % 4 == 0) and (year % 100 > 0))):
print(f"{year} is leap year")
else:
print(f"{year} is not leap year")
If you really want to check if a variable is of type float try this with different values for year:
year_div_4 = year / 4
if (isinstance(year_div_4, float)):
print(f"{year_div_4} is of type float")
print(f"type is {type(year_div_4)}")
You will see that the type doesn't help you for a divisibility check, because in python the result of year / 4 will always be of type float even if year is divisible by 4.
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 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
I am trying to create a program that finds out how many months they have been alive, but have been running into some issues. Here is my function so far:
int getResult(int year, month, day, endResult)
{
int thisYear, thisMonth, thisDay;
year = thisYear - year;
year *= 12;
}
And what I'm trying to accomplish would show an output like:
Output:
What year were you born?
1989
What month were you born?
5
What day were you born?
23
You are x months old.
I was going to continue with months but then I realized, what if the month they were born is in after this month or before? So, if anyone has any tips on how to calculate that, I'd appreciate it.
Let's see. First, let's say now is:
year_now and month_now
and your birthday is:
year_birth and month_birth
Now, we go case by case:
month_now == month_birth: as you have already computed:
months_old = (year_now-year_birth)*12
month_now > month_birth: easily, you have:
months_old = (year_now-year_birth)*12 + (month_now-month_birth)
month_now < month_birth: in this case, (year_now-year_birth)*12 gives you more months then necessary, and you have to subtract:
months_old = (year_now-year_birth)*12 - (month_birth-month_now)
Now if you look carefully, you will see that they are all in fact the same formula:
months_old = (year_now-year_birth)*12 + (month_now-month_birth)
(in the third case, month_now-month_birth is negative)
months = (thisyear-years)*12+(thisMonth-months)
if(months < 0)
System.out.println("Invalid info")
else{
//DO YOUR THANG BRO
}