Weekly Loan payment/ Amortization Schedule Calculation logic in c# - c#

I have completed Loan Amortization/ Loan Repayment calculation for monthly. Now i required for weekly calculation formula in c#.
Can any one please help me to answer this?
Here loan amount is 10000, Interest Rate is 10% and Terms 7 Months
This is my monthly calculation. but i need weekly calculation like this
loanAmount = 10000;
var periods = 7; //Months
var monthlyRate = (Convert.ToDouble(10) / 100) / 12;
var monthlyPayment = Math.Round(monthlyRate / (1 - Math.Pow((1 + monthlyRate), -(periods))) * loanAmount ,2);
Thanks in advance,
Mani

Without seeing exactly how you are calculating it, it should be as simple as switching out months for weeks. For example, instead of something like this:
monrthly payments = (balance * APR) / 12 months
Do this:
weekly payments = (balance * APR) / 52 weeks
Obviously you'll change it depending on what you're calculating and how you're calculating it. You've already done the hard part now you just have to change the time frame, does that make sense?

Related

How to do calculations price calculation based on time and wage

I am trying to figure out final price based on wage multiplied by hours.
Here is my code
Why if the hours are 02:30:00 and the wage: $14 is my total 2?
TimeSpan duration = TimeSpan.Parse("02:30:00");
int wage = 14;
var result = (duration.Hours + (duration.Minutes / 60) * wage);
First, the expression is actually evaluated as:
duration.Hours + ((duration.Minutes / 60) * cleaner.Price)
Second, you are doing integer division, so 30/60 will result in 0, leaving you with the value 2 i.e. the Hours part.
To fix the issue, you can do something like the below:
(duration.Hours + ((decimal)duration.Minutes / 60)) * 14;
Alternatively, you can skip this component-wise calculation, and just use the TotalHours property instead:
duration.TotalHours * 14

calculate uptime/downtime for a service

I have a custom solution that checks if a web-site is online, every 1 hour.
The result is something like this: (there is one entry per day)
There are 24 entries in a day (every hour). And every hour has a availability percentage (100%, 95%, 0% ... and so forth).
My questions are:
how can I get up-time and downtime in percentage?
how can I calculate up-time and downtime using these values between 2 dates DateTime and get the result in seconds?
The up-time is easy:
sum of all values divided by 24 (entries) which is 99.67%
Then for downtime, can I just do 100 - 99.67 = 0.33 % ?
I have some issues in getting the up-time/downtime in seconds between 2 dates DateTime
For example: if the range dates are 20.04.2015 - 26.05.2015
I think I should do like this:
For each day calculate the up-time as above (sum of all daily values divided by 24 entries) and assuming the following values:
20.04.2015: 96.67%
21.04.2015: 100.00%
22.04.2015: 92.00%
23.04.2015: 96.67%
24.04.2015: 100.00%
25.04.2015: 100.00%
26.04.2015: 100.00%
Now the sum of the above values divided by the number of days (7 days between 20.04 and 26.04) which makes 97.91 % availability between 20.04 and 26.04.
I assume to get 97.91 % up-time in seconds I should do like this:
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime first = DateTime.ParseExact("20.04.2015", "dd.MM.yyyy", provider);
DateTime last = DateTime.ParseExact("26.04.2015", "dd.MM.yyyy", provider);
TimeSpan time = last - first;
decimal secondsUptime = ((time.Days * 86400)/100) * 97.91m; //97.91 is the uptime calculated above for the time period.
// The problem is how to get this?
decimal secondsDowntime = ?
What I have done so far, is this the correct approach?
How to get the secondsDowntime?
If you already have the Up time percent, All you have to do is very simple math:
decimal PercentDownTime = 100 - PercentUpTime;
decimal SecondsUpTime = (time.Seconds / 100) * PercentUpTime;
decimal SecondsDownTime = (time.Seconds / 100) * PercentDownTime;
Thanks to Robert for reminding us the TotalSeconds property of TimeSpan, but In this case it's ok to use the Seconds property.
Hold up... Ur input numbers are wrong. If u measure once per hour and display the hourly results than how does ur 11:00 have 97%? It should be 100% or 0% its either up or down that hour.... Unless u actually do more calculations in that hour... But even then to get 97 u would have to do at least 100 tests that hour and 3 of them were down.
But if ur numbers are correct the formulas are this...
Uptime % = (sum of the uptime percentages) / (number of measurements) × 100
Uptime % = (sum of uptime) / 24 × 100
Downtime % = 100 - (uptime %)
Seconds of uptime = (number of hours measured or to consider) × 3600 × (uptime %) / 100
Seconds of downtime = (number of hours measure or to consider × 3600) - (seconds of uptime)
Note 3600 is the number of sec in an hour so we multiply the hours by that to get us to the wanted time unit of seconds.
Note Replace uptime % with a number between 0 and 100. Not 0 and 1. If u use 0 to 1 then dont do the last division by 100.

Multiplying fractions in safe way c#

I am trying to work out how to work out the total cost of a vehicle repair job in a numerically safe way, avoiding rounding errors. I get the amount of time spent on a job, then multiply it by a constant labour rate value to get the correct amount cost of labour, however it is not working out how it should be. Here is my example when there has been 20 minutes spent on the job.
This clearly works out wrong as a third of £30 is £10, so how do I avoid the rounding error I am getting?
Here is how I get the total time.
TimeSpan totalTime = TimeSpan.Zero;
foreach (DataRow timeEntry in dhJob.DataStore.Tables[jobTimeCollectionName].Rows)
{
DateTime start = Convert.ToDateTime(timeEntry["jobtimestart"]);
DateTime end = Convert.ToDateTime(timeEntry["jobtimeend"]);
totalTime += (end - start);
}
tb_labourtime.Text = Convert.ToString(Math.Round(totalTime.TotalHours, 2));
tb_labourtotal.Text = (Convert.ToDouble(tb_labourtime.Text) * Convert.ToInt32(tb_labourrate.Text)).ToString();
Any help / advice is appreciated.
Firstly, you are converting the totalTime to a string representation which only has two digits of precision, which is not going to be very accurate.
Secondly, when doing financial calculations, you should generally use the decimal type rather than the double type, which will give you greater accuracy(although it still isn't completely accurate).
The first thing to do is to use the totalTime to calculate the total wages rather than using a converted string value:
tb_labourtotal.Text = (totalTime.TotalHours * Convert.ToInt32(tb_labourrate.Text)).ToString();

Time to Temperature Calculation

This might not be the correct place for this, so apologies in advance if it isn't.
My situation - I need to come up with a simple formula/method of giving it an hour E.g. 13, 15, 01 etc, and based on that number, the method will return the 'approx' temperature for that particular time.
This is very approximate and it will not use weather data or anything like that, it will just take the hour of the day and return a value between say -6 deg C > 35 deg C. (very extreme weather, but you get the idea.)
This is the sort of examples I would like to know how to do:
Just as a note, I COULD use an ugly array of 24 items, each referencing the temp for that hour, but this needs to be float based - e.g. 19.76 should return 9.25 deg...
Another note: I don't want a complete solution - I'm a confident programmer in various languages, but the maths have really stumped me on this. I've tried various methods on paper using TimeToPeak (the peak hour being 1pm or around there) but to no avail. Any help would be appreciated at this point.
EDIT
Following your comment, here is a function that provides a sinusoidal distribution with various useful optional parameters.
private static double SinDistribution(
double value,
double lowToHighMeanPoint = 0.0,
double length = 10.0,
double low = -1.0,
double high = 1.0)
{
var amplitude = (high - low) / 2;
var mean = low + amplitude;
return mean + (amplitude * Math.Sin(
(((value - lowToHighMeanPoint) % length) / length) * 2 * Math.PI));
}
You could use it like this, to get the results you desired.
for (double i = 0.0; i < 24.0; i++)
{
Console.WriteLine("{0}: {1}", i, SinDistribution(i, 6.5, 24.0, -6.0, 35.0));
}
This obviously discounts environmental factors and assumes the day is an equinox but I think it answers the question.
So,
double EstimatedTemperature(double hour, double[] distribution)
{
var low = Math.Floor(hour);
var lowIndex = (int)low;
var highIndex = (int)Math.Ceiling(hour);
if (highIndex > distribution.Count - 1)
{
highIndex = 0;
}
if (lowIndex < 0)
{
lowIndex = distribution.Count - 1;
}
var lowValue = distribution.ElementAt(lowIndex);
var highValue = distribution.ElementAt(highIndex);
return lowValue + ((hour - low) * (highValue - lowValue));
}
assuming a rather simplistic linear transition between each point in the distibution. You'll get erroneous results if the hour is mapped to elements that are not present in the distribution.
For arbitrary data points, I would go with one of the other linear interpolation solutions that have been provided.
However, this particular set of data is generated by a triangle wave:
temp = 45*Math.Abs(2*((t-1)/24-Math.Floor((t-1)/24+.5)))-10;
The data in your table is linear up and down from a peak at hour 13 and a minimum at hour 1. If that is the type of model that you want then this is really easy to put into a formulaic solution. You would just simply perform linear interpolation between the two extremes of the temperature based upon the hour value. You would have two data points:
(xmin, ymin) as (hour-min, temp-min)
(xmax, ymax) as (hour-max, temp-max)
You would have two equations of the form:
The two equations would use the (x0, y0) and (x1, y1) values as the above two data points but apply them the opposite assignment (ie peak would be (x0, y0) on one and (x1, y1) in the other equation.
You would then select which equation to use based upon the hour value, insert the X value as the hour and compute as Y for the temperature value.
You will want to offset the X values used in the equations so that you take care of the offset between when Hour 0 and where the minimum temperature peak happens.
Here is an example of how you could do this using a simple set of values in the function, if you wish, add these as parameters;
public double GetTemp(double hour)
{
int min = 1;
int max = min + 12;
double lowest = -10;
double highest = 35;
double change = 3.75;
return (hour > max) ? ((max - hour) * change) + highest : (hour < min) ? ((min - hour)*change) + lowest : ((hour - max) * change) + highest;
}
I have tested this according to your example and it is working with 19.75 = 9.6875.
There is no check to see whether the value entered is within 0-24, but that you can probably manage yourself :)
You can use simple 2 point linear approximation. Try somthing like this:
function double hourTemp(double hour)
{
idx1 = round(hour);
idx2 = idx1 + 1;
return (data[idx2] - data[idx1]) * (hour - idx1) + data[idx1];
}
Or use 3,5 or more points to get polynom cofficients with Ordinary Least Squares method.
Your sample data similar to the sin function so you can make sin function approximation.

Getting a Weighted Average Date Value?

If I have 50% weight on 6/3/2011 and 50% weight on 6/1/2011, the weighted average will be 6/2/2011.
Now, I can't seem to figure out how I can do this with uneven weights, since it's not like you can multiply a DateTime by a double, and sum up the results (or can you?).
DateTime dateA = ...;
DateTime dateB = ...;
TimeSpan difference = dateA - dateB;
double units = difference.Ticks;
// Do your weighted logic here on 'units'.
DateTime average = dateA + new TimeSpan(units);
Something like the above (you get the idea - basically need to normalise the difference into a format you can work with, i.e. ticks, etc.).
You can find the difference between two dates(start and end) in terms of days. Apply the weight on the difference_days and get the final output date by startdate + weightedDays
You can't multiply a datetime by a double, but you can set a value for date1 and date2 on a scale (1 to 100) and figure out where the value you would be in the middle. The 1 versus 100 ends up on 50 in your 50/50 scenario.
You then have to figure the number of days in the range. You can then multiply by the weighted decimal (as a percent) and turn that into number of days. Then add that number of days to the first value.
Since you can turn dates into numbers, this gives some pretty interesting other means of accomplishing this. A TimeSpan is one way of setting this up as a number.
Use the long timestamps of the DateTime Objects.
Can you use the Ticks property of DateTime? Something like:
DateTime firstDate = new DateTime(2011, 6, 5);
DateTime secondDate = new DateTime(2011, 6, 1);
double weight1 = 0.4;
double weight2 = 0.6;
var averageTicks = (firstDate.Ticks * weight1) + (secondDate.Ticks * weight2) / 2;
DateTime averageDate = new DateTime(Convert.ToInt64(averageTicks));
I think the weighted average formula would be sumproduct (Weights*Dates)/sum (Weights)
Where sumproduct means the sum of all factors. Factors being the multiplication of weights and date.ticks. If sum of weights=1 then only the numerator remains.
i had the same problem, only with money(cashflows) which means there is a compounding\discounting rate of growth\decay of value known as time value of money)...
In order to enable you to avoid that mistake i composed a spreadsheet found at:
https://1drv.ms/x/s!AqGuYeJW3VHggc9ARWCxcHIeodd2Pg
You just have to experiment with it!!!...And understand that at 0% interest rate the results are identical to the weighted average described in other posts but as rate increases there is deviation. Then you gotta build an XNPV function for your programming language and fuse it with your app.
also there are a number of examples with growth in algebra books.maybe there is an intersection with them and datetime-offsets found in cashflows

Categories