Question #1: (use while loop only)
An auto repair shop in Miami estimates that, your vehicle will cost $1689 to repair. Assuming that you could not afford to come up with such amount up front, the repair shop offers to let you pay the total repair cost ($1689) by installment, but at an annual interest rate of 3.00% compounded monthly.
Using a while loop,
Display the remaining balance after each month until pay off
Example/Hint: Balance will be $1,493.22 after 1 month.
Using the output from item 1 above, determine how many months will the vehicle be three quarter
(¾) paid off? Use a print statement to display the message.
Example: "Repair cost total will be 3/4 paid off in 2 months"
I am struggling to figure out how to attack this problem. I'm not sure how to calculate how much each monthly payment will be. There is a hint within the question that in one month, your repair cost goes from $1689 to $1493.22, implying that for the first month, you paid off $195.78 of the repair cost. Any help on how to even start this problem would be much appreciated, thank you.
Your first step is to calculate how much the client is paying per month and with that information apply the "compound interest with monthly withdrawals" formula.
To calculate that, you first calculate how much the balance will be after one month with interest:
monthly_interest_rate = annual_interest_rate / 12
balance += (balance * monthly_interest_rate)
Now subtract the balance after one month gave as a tip from the balance calculated above:
balance_after_one_month = 1493.22
paid_monthly_by_customer = balance - balance_after_one_month
Related
So for argument sake here is an example of autoarima for daily data:
auto_arima(df['orders'],seasonal=True,m=7)
Now in that example after running a Seasonal Decomposition that has shown weekly seasonality I "think" you select 7 for m? Is this correct as the seasonality is shown to be weekly?
My first question is as follows - If seasonality is Monthly do you use 12? If it is Annually do you use 1? And is there ever a reason to select 365 for daily?
Secondly if the data you are given is already weekly e.g
date weekly tot
2021/01/01 - 10,000
2021/01/07 - 15,000
2021/01/14 - 9,000
and so on......
And you do the seasonal decomposition would m=1 be used for weekly, m=4 for monthly and m=52 for annually.
Finally if its monthly like so:
date monthly tot
2020/01/01- 10,000
2020/02/01- 15,000
2020/03/01- 9,000
and so on......
And you do the seasonal decomposition would m=1 for monthly and m=12 for annually.
Any help would be greatly appreciated, I just want to be able to confidently select the right criteria.
A season is a recurring pattern in your data and m is the length of that season. m in that case is not a code or anything but simply the length:
Imagine the weather, if you had the weekly average temperature it will rise in the summer and fall in the winter. Since the length of one "season" is a year or 52 weeks, you set m to 52.
If you had a repeating pattern every quarter, then m would be 12, since a quarter is equal to 12 weeks. It always depends on your data and your use case.
To your questions:
If seasonality is Monthly do you use 12?
If the pattern you are looking for repeats every 12 months yes, if it repeats every 3 months it would be 3 and so on.
If it is Annually do you use 1?
A seasonality of 1 does not really make sense, since it would mean that you have a repeating pattern in every single data point.
And is there ever a reason to select 365 for daily?
If your data is daily and the pattern repeats every 365 days (meaning every year) then yes (you need to remember that every fourth year has 366 days though).
I hope you get the concept behind seasonality and m so you can answer the rest.
I am a beginner in Python. I'm using the mip package to optimize a standalone battery given hourly power price in a year. I need the program to pick 5 lowest price hours to charge the battery and 4 highest price hours to discharge it every day for a year. But first I'm trying out the solver for 24 hours.
Data:
time, month, day, hour, power price (24 entries)
Q:
Solve for a standalone battery's optimal charging and discharging pattern
Battery rating: 1MW with 4MWh storage capability (4-hour storage)
Output: two columns of binary variables
Battery needs 4.7 hours to fully charge, and discharges for 4 hours
Round-trip efficiency 85%, charging 1 hour enables discharging of 0.85 hour
Constraints:
Battery state: available power >0 (cumulative charge - cumulative discharge) > 0
0 < cumulative discharge < 4
0 < cumulative charge < 4.7
Below is my code:
import numpy as np
import pandas as pd
import mip
from mip import Model, xsum, maximize, BINARY, CONTINUOUS, OptimizationStatus
# Define model and var
m = mip.Model(sense=maximize)
maxdischargepower = 4
maxchargepower = 4.7
H = 24
charge = [m.add_var(var_type = BINARY) for i in range(H)]
discharge = [m.add_var(var_type = BINARY) for i in range(H)]
batterystate = np.cumsum(charge) - np.cumsum(discharge)
# Define objective function
m.objective = xsum(discharge[i]*price[i] for i in range(H)) - xsum(charge[i]*price[i] for i in range (H))
# Constraints
m += np.cumsum(discharge) <= maxdischargepower
m += np.cumsum(charge) <= maxchargepower
m += np.cumsum(discharge) >= 0
m += batterystate >= 0
I have several questions:
I get a result of -1277, which is the opposite number of the sum of power price in 24 hours. There must be something wrong with the optimizing code but I cannot find it.
How do I save the charge and discharge binaries in the input data file?
Should I iterate the optimization model for 365 days for year-round data?
Thank you.
---------------------Edit 2/19-------------------------
Here's some sample data I've been running the code on:
Or in fact, 24 random numbers would also work but these are the actual prices I've been using.
I have an entire year of the data and once I figure out how to optimize within a day should I iterate the optimization for 366 days?
sample data
Seems like the main part of the algorithm is to ask these questions at the top of each hour:
At what time will the battery be discharged?
Which hour between now and then will be the cheapest for recharging?
IF that is the current hour, then turn on recharging.
It seems like that would be optimal if you can recharge in less than an hour. I don't understand the numbers you have -- 4 and 4.7 -- sounds like you need to be recharging almost all the time.
If that is the case, the algorithm can be turned around to "avoid recharging during costly hours".
You can't wait too long to decide whether to charge or not. I assume the cost of making the decision is essentially zero. So, recompute every hour (at least) and don't reach forward too far. It sounds like you have less than 5 hours before the battery will die; trying to optimize further into the future will be useless if it is dead.
I'm trying to program a salary calculator that tells you what your salary is during sick leave. In Costa Rica, where I live, salaries are paid bi-monthly (the 15th and 30th of each month), and each sick day you get paid 80% of your salary. So, the program asks you what your monthly salary is and then asks you what was the start date and finish date of your sick leave. Finally, it's meant to print out what you got paid each payday between your sick leave. This is what I have so far:
import datetime
salario = float(input("What is your monthly salary? "))
fecha1 = datetime.strptime(input('Start date of sick leave m/d/y: '), '%m/%d/%Y')
fecha2 = datetime.strptime(input('End date of sick leave m/d/y: '), '%m/%d/%Y')
diasinc = ((fecha2 - fecha1).days)
print ("Number of days in sick leave: ")
print (diasinc)
def daterange(fecha1, fecha2):
for n in range(int ((fecha2 - fecha1).days)):
yield fecha1 + timedelta(n)
for single_date in daterange(fecha1, fecha2):
print (single_date.strftime("%Y-%m-%d")) #This prints out each individual day between those dates.
I know for the salary I just multiply it by .8 to get 80% but how do I get the program to print it out for each pay day?
Thank you in advance.
Here's an old answer to a similar question from about eight years ago: python count days ignoring weekends ...
... read up on the Python: datetime module and adjust Dave Webb's generator expression to count each time the date is on the 15th or the 30th. Here's another example for counting the number of occurrences of Friday on the 13th of any month.
There are fancier ways to shortcut this calculation using modulo arithmetic. But they won't matter unless you're processing millions of these at a time on lower powered hardware and for date ranges spanning months at a time. There may even be a module somewhere that does this sort of thing, more efficiently, for you. But it might be hard for you to validate (test for correctness) as well as being hard to find.
Note that one approach which might be better in the long run would be to use Python: SQLite3 which should be included with the standard libraries of your Python distribution. Use that to generate a reference table of all dates over a broad range (from the founding of your organization until a century from now). You can add a column to that table to note all paydays and use SQL to query that table and select the dates WHERE payday==True AND date BETWEEN .... etc.
There's an example of how to SQLite: Get all dates between dates.
That approach invests some minor coding effort and some storage space into a reference table which can be used efficiently for the foreseeable future.
I am query AWS pricing using boto ec2 in python.
Firstly,I am finding all offering instances of particular instance type using get_all_reserved_instances_offerings ,
then for all instances return by above, I am checking amount and fixed price in 'hourly frequency'. I do this by this code:
for ins in each_ins.recurring_charges:
if ins.frequency == 'Hourly':
print float(ins.amount)
print float(each_ins.fixed_price)
each_ins.fixed_price prints upfront correctly
"d2.2xlarge": 3844.0,
"m3.2xlarge": 1961.0,
it shows correct price as shown in picture with red mark:
But ins.amount prints:
"d2.2xlarge": 0.438,
"m3.2xlarge": 0.248,
I think it should be 0.8768 as shown in above picture with green mark.
The values in the green box are the overall effective cost of the instances per hour over the year (i.e. accounting for the per hour charge over the year plus the initial up-front cost spread over the year.)
However the ins.amount value is the cost charged per hour each month, ignoring the initial up-front cost. Roughly calculating over a month from the monthly cost gives an hourly cost of ~0.444, pretty much corresponding to the values you're seeing.
AWS says the following with respect to the continuing monthly charges:
*This is the average monthly payment over the course of the RI term. For each month, the actual monthly payment will equal the actual number of hours in that month multiplied by the hourly usage rate. The hourly usage rate is equivalent to the total average monthly payments over the term of the RI divided by the total number of hours (based on a 365 day year) over the term of the RI.
I've got an assignment for my MITx CS class and I am stuck on the following problem:
The following variables contain values as described below:
balance - the outstanding balance on the credit card
annualInterestRate - annual interest rate as a decimal
To recap the problem: we are searching for the smallest monthly
payment such that we can pay off the entire balance within a year.
What is a reasonable lower bound for this payment value? $0 is the
obvious anwer, but you can do better than that. If there was no
interest, the debt can be paid off by monthly payments of one-twelfth
of the original balance, so we must pay at least this much every
month. One-twelfth of the original balance is a good lower bound.
What is a good upper bound? Imagine that instead of paying monthly, we
paid off the entire balance at the end of the year. What we ultimately
pay must be greater than what we would've paid in monthly
installments, because the interest was compounded on the balance we
didn't pay off each month. So a good upper bound for the monthly
payment would be one-twelfth of the balance, after having its interest
compounded monthly for an entire year.
In short:
Monthly interest rate = (Annual interest rate) / 12.0 Monthly payment
lower bound = Balance / 12 Monthly payment upper bound = (Balance x (1
+ Monthly interest rate)12) / 12.0
Write a program that uses these bounds and bisection search (for more
info check out the Wikipedia page on bisection search) to find the
smallest monthly payment to the cent (no more multiples of $10) such
that we can pay off the debt within a year. Try it out with large
inputs, and notice how fast it is (try the same large inputs in your
solution to Problem 2 to compare!). Produce the same return value as
you did in Problem 2.
Now, this is what I've been able to come up with but it actually generates a wrong output. I have no idea what's going on wrong with this code:
#------------Defined variables---------------#
balance = 999999
annualInterestRate = 0.18
#------------Defined variables---------------#
monthlyInterestRate = annualInterestRate / 12.0
monthlyPaymentLower = balance / 12
monthlyPaymentUpper = (balance * (1 + monthlyInterestRate)**12) / 12.0
month = 1
total = 0
while (total < balance) and month < 13:
pay = (monthlyPaymentLower + monthlyPaymentUpper) / 2
total += pay
if total < balance:
monthlyPaymentLower = pay
elif total > balance:
monthlyPaymentHigher = pay
month += 1
if month == 13:
total = 0
month = 1
print 'Lowest Payment: ' + str(round(pay, 2))
Help?
Like always, not looking for a complete solution or the source code, just drop some hints on where I've gone wrong. (I always get negative votes. :/ )
In place
total += pay
you have to count balance for 12 mount like in problem 2
for month in range(12):
balance = balance - pay
balance = balance + monthlyInterest
than you have to compare balance with 0 and change monthlyPaymentLower or monthlyPaymentUpper
You have to compare monthlyPaymentLower to monthlyPaymentUpper to see if you can finish
if monthlyPaymentUpper - monthlyPaymentLower < 0.001 :
print "now I can finish searching"
Of course in this situation you will have to change more things in your code :)