Calculating APR - c#

So, as the title says I need to calculate the APR for a loan. I have the following:
apr = (rate * ((Math.Pow((1 + rate), duration))) /
((Math.Pow((1 + rate), duration)) - 1)) -
(installment / (loanamount - extracost));
But its not returning the correct value. I also tried another version of that equation with even worse results:
apr = ((loanamount + extracost) * rate * Math.Pow((1 + rate), duration)) / (Math.Pow((1 + rate),duration) - 1);
The calculations are all wrong. I tried adjusting some parenthesis and checking the order of operations. Any help would be greatly appreciated!

Maybe it sounds like cheating, but I just used the existing VB financial library .NET has. Its for annuities so you have to make the payment a negative number.
Term is full number of payments(i.e. 15 year mortgage has 180 payments so 180)
Payment is payment per (so monthly payment amt... x -1)
Starting Amount = original loan amount with no fees
double apr = Microsoft.VisualBasic.Financial.Rate(term,-payment,originalLoanAmt)
Then just multiply by the answer by the annual # of payments (if monthly then 12) or if you want the % expressed as a number like 3.25%, then multiply by 100 as well.
**note you have to add a reference to Microsoft.VisualBasic assembly.

You're calculating the payment amount given duration as the number of payments. That's not the APR. Here's what I'm seeing:
double apr, loanamount = 3000d, extracost = 7000d, rate = 0.05;
int duration = 1;
apr = ((loanamount + extracost) * rate * Math.Pow((1 + rate), duration)) / (Math.Pow((1 + rate),duration) - 1);
Console.WriteLine(apr);
duration = 2;
apr = ((loanamount + extracost) * rate * Math.Pow((1 + rate), duration)) / (Math.Pow((1 + rate),duration) - 1);
Console.WriteLine(apr);
duration = 3;
apr = ((loanamount + extracost) * rate * Math.Pow((1 + rate), duration)) / (Math.Pow((1 + rate),duration) - 1);
Console.WriteLine(apr);
where the output is
10500
5378.0487804878
3672.08564631245
Only the first answer is the same as what you might expect from A=Pe^(rt) or similar calculations of the amount from the principal.
The actual calculation you need depends on both the legal jurisdiction and the type of credit/loan though.

Related

How do I show cents when I am writing a code to count total money, the code below is only showing a whole number (such as $1)

I am trying to write a code in C# that prints out the total of dollars and cents I have. I have the first part done, but the end of the code won't show how much cents there is when I run the whole code, it only shows a whole number (such as $1), when I need the code to show something like $1.56. What am I missing in the program in order to show this?
Console.WriteLine("Enter number of quarters: ");
int quarters = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter number of dimes: ");
int dimes = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter number of nickels: ");
int nickels = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter number of pennies: ");
int pennies = Convert.ToInt32(Console.ReadLine());
double dollars = (int)(((quarters * 0.25) + (dimes * 0.10) + (nickels * 0.05) + (pennies * 0.01)) % 1 * 100);
Console.WriteLine("Your total is $" + dollars);
When I typed in 4 quarters, 0 dimes, 0 nickels, and 1 penny, it shows the result as $1 not $1.01
You are forcing the result as int, so the decimals are cut
double dollars = (int)(((quarters * 0.25) + (dimes * 0.10) + (nickels * 0.05) + (pennies * 0.01)) % 1 * 100);
Do not force to int, on the contrary, force to double
double dollars = ((quarters * 0.25) + (dimes * 0.10) + (nickels * 0.05) + (pennies * 0.01)) % 1 * 100;
But, since you are handling money, I would recommend to handle everything with decimal
decimal dollars = ((quarters * 0.25) + (dimes * 0.10) + (nickels * 0.05) + (pennies * 0.01)) % 1 * 100;
Better explained in dotnet perls
Decimal accurately stores numeric data. The .NET Framework offers this
type for programs where rounding errors are harmful. Decimal stores
large and small numbers with many digits after the decimal place.
EDIT
When I put in decimal dollars instead of double dollars, I then get
the error, "Cannot implicitly convert type 'double' to 'decimal'. An
explicit conversion exists (are you missing a cast?)
It is becuse you need all the operation of the same type, you can do
int quarters =1;
int dimes = 1;
int nickels = 1;
int pennies = 1;
decimal dollars = ((quarters * 0.25m) + (dimes * 0.10m) + (nickels * 0.05m) + (pennies * 0.01m)) % 1 * 100;
Console.WriteLine("Your total is $" + dollars);
Note the use of a m after the number, this is to tell the compiler that the type is decimal or Money, not double.

More efficiƫnt way for reoccuring modulo?

I originally tried this with modulo but it did not work as expected
It keps giving me back the value(my teacher and I both couldn't figure it out)
Example:
Uw krijgt 200 x 2 euro terug
Uw Krijgt 100 x 1 euro terug
Uw krijgt 50 x 50 cent terug
Etc...
What it's supposed to do
I need to make a program that calculates howmuch change you get back.
Input 5
Cost: 2
Output: 1x 2 euro, 1x 1 euro, 0 x 50 cents, ...
My code
int Prijs, Ingegooid;
int Cent1, Cent2, Cent5, Cent10, Cent20, Cent50, Euro, Euro2, Wisselgeld;
private void btnCola_Click(object sender, RoutedEventArgs e)
{
Cent10 = 10;
Cent20 = 20;
Cent50 = 50;
Euro = 100;
Euro2 = 200;
Ingegooid = Convert.ToInt32(txbIngegooid.Text);
Prijs = 190;
Wisselgeld = (Ingegooid * 100 - Prijs);
Euro2 = Wisselgeld / Euro2;
MessageBox.Show("Uw krijgt " + Euro2 + " aantal 2 euro stukken terug.");
Euro = (Wisselgeld-Euro2*200) / Euro;
MessageBox.Show("Uw krijgt " + Euro + " aantal 1 euro stukken terug.");
Cent50 = (Wisselgeld-Euro2*200-Euro*100) / Cent50;
MessageBox.Show("Uw krijgt " + Cent50 + " aantal 50 cent stukken terug.");
Cent20 = (Wisselgeld-Euro2*200-Euro*100-Cent50*50) / Cent20;
MessageBox.Show("Uw krijgt " + Cent20 + " aantal 20 cent stukken terug.");
Cent10 = (Wisselgeld-Euro2*200-Euro*100-Cent50*50-Cent20*20) / Cent10;
}
You do not necessarily need modulo for this.
In this case it could actually be misleading.
Example: 90 Cents:
1 possible way to solve this:
1*50c + 2*20c.
Another way would be:
4*20c + 1*10c.
If you want to use the biggest coin whenever possible you could do it this way if you really want to:
10centAmmount = (change % 50) % 20;
In this case
10centAmmount = (90 % 50) % 20;
(90 % 50 = 40; 40 % 20 = 0 -> You do not need any 10 cent coins)
Working from the biggest coins to the smallest makes a lot more sense here.
I also recommend substracting the coins you already used from the change. Since the code gets "less crowded"
Euro2 = change/200;
change -= Euro2 * 200
Euro1 = change/100
change -= Euro1 * 100
...
A use case for modulo would be to figure out whether a number is dividable by any other number.
Example:
if (a % 4 == 0) {
print "a can be devided by 4";
Also the code is sort of confusing. You used Euro2 for the amount of cents a Euro coin has, but later you used it to count the number of 2 Euro coins. It would be a little less confusing if you used different variables for this. You could also use constants for values you never need to change, like the cent ammount of 2 euro coins.
Hope this sort of helps.

convert string "172406" to integers 17, 24, 06 fast

I need to convert fast the string in format "HHmmss" to DateTime or integers. I've tested such code:
Console.WriteLine("decoding " + text);
long microseconds = sw.ElapsedTicks / (Stopwatch.Frequency / (1000L * 1000L));
Console.WriteLine("start time " + microseconds);
field = DateTime.ParseExact(text, "HHmmss", null);
microseconds = sw.ElapsedTicks / (Stopwatch.Frequency / (1000L * 1000L));
Console.WriteLine("finish time " + microseconds);
and the output is
decoding 172400
start time 121
finish time 244
decoding 172400
start time 236
finish time 383
decoding 172400
start time 116
finish time 416
decoding 172400
start time 235
finish time 421
decoding 172359
start time 149
finish time 323
so in average about 150 microseconds. What's a lot of time, i'm writing HFT software and the best HFT has in average 10 microseconds "tick-to-trade" time (this includes everything!). I understand that using c# this is imposible however i still think that 150 microseconds is too much even using c#.
Now I want to use another algorithm, however I don't know how to "extract" integers from the text:
field = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, /*extract hour, min, sec from text*/)
What can you suggest and what would be the fastest way?
Please do not ask why I'm care about perfomance instead just suggest how to do that faster.
Results:
Using DateTime.ParseExact(text, "HHmmss", null) about 6-8 ticks
Using TimeSpan ts = TimeSpan.ParseExact(text, "hhmmss", null); about 3-4 ticks
Using int hour = 10 * text[0] + text[1] - 11 * '0';... about 0 ticks
Acutally much less than 0 ticks if using loop for measurements. Actually it was found that last version is 100 times faster than other.
Code:
long startMicroseconds = sw.ElapsedTicks /*/ (Stopwatch.Frequency / (1000L * 1000L))*/;
//TimeSpan ts = TimeSpan.ParseExact(text, "hhmmss", null);
//int hour = 10 * text[0] + text[1] - 11 * '0';
//int minute = 10 * text[2] + text[3] - 11 * '0';
//int second = 10 * text[4] + text[5] - 11 * '0';
field = DateTime.ParseExact(text, "HHmmss", null);
long finishMicroseconds = sw.ElapsedTicks /*/ (Stopwatch.Frequency / (1000L * 1000L))*/;
Console.WriteLine("elappsed " + (finishMicroseconds - startMicroseconds));
This approach doesn't use any string substring or parsing methods. It uses only indexing and simple arithmetic:
int hour = (s[0] - '0') * 10 + s[1] - '0';
int minute = (s[2] - '0') * 10 + s[3] - '0';
int second = (s[4] - '0') * 10 + s[5] - '0';
This next version is probably even faster because the calculation has been partially evaulated to help the compiler. As a result it is slightly harder to read and understand:
int hour = s[0] * 10 + s[1] - '0' * 11;
int minute = s[2] * 10 + s[3] - '0' * 11;
int second = s[4] * 10 + s[5] - '0' * 11;
For kicks you might also want to see if this is even faster, though I suspect that this code will be the same as the previous version:
int hour = s[0] * 10 + s[1] - 528;
int minute = s[2] * 10 + s[3] - 528;
int second = s[4] * 10 + s[5] - 528;
If you really want performance instead of readability you can work with raw chars directly:
hour = 10*s[0] + s[1] - 11*'0';
minute = 10*s[2] + s[3] - 11*'0';
second = 10*s[4] + s[5] - 11*'0';
btw. DateTime.Now is quite slow because it needs to convert the current time to the local time-zone. You should use DateTime.UtcNow instead. On my comp DateTime.UtcNow costs 9ns, DateTime.Now costs 900ns.
You also should fetch DateTime.UtcNow only once, else you get a race-condition.
Is this really too slow?
TimeSpan ts = TimeSpan.ParseExact("172406", "hhmmss", null);
int hh = ts.Hours;
int mm = ts.Minutes;
int ss = ts.Seconds;
It is at least easy to understand.

Translating Excel formula to c# (annuity)

I have a excel formula I am trying to "translate" into c# code.
It is used to calculate an "annuity rate" over time (for example 20 years).
=(((1+E26/100)^D28*((1+E26/100)-1))/((1+E26/100)^D28-1))*100
D28 = 20 (years)
E26 = 5,00 (the rate in percent)
the ^ stands for exponent in Excel
As a result with these numbers I expect 8,02% per annum.
I tried several approaches using Math.Pow but wasn't successful.
Here is my first approach which gives me a result of 5 somehow.
double usagePanels = 20.0
double rate = 5.0
annPanels = (Math.Pow((1 + rate / 100), usagePanels) *
((1 + rate / 100) - 1) /
Math.Pow(1+rate/100, (usagePanels-1))) * 100;
Thank you.
Try:
double usagePanels = 20.0
double rate = 5.0
double annPanels = (Math.Pow((1 + rate / 100), usagePanels) *
(rate / 100.0)) /
Math.Pow(1+rate/100, usagePanels)-1)) * 100;
You've got the closing bracket, between usagePanels and the -1, wrong...
(I found this by breaking the formula apart in Excel and in C# and comparing each part.)
EDIT: Another handy tip for comparing Excel to C# is to give the cells in Excel a name (via the Named Range feature) that way the Excel formula can be made to look closer to variable names...
This should do the trick:
double rate = 5;
double years = 20;
double annunity = Math.Pow(1 + rate / 100, years) * (rate / 100) / Math.Pow(1 + rate / 100, years - 1) * 100;
For clarity, the working result is
double usagePanels = 20.0
double rate = 5.0
annPanels = (Math.Pow((1 + rate / 100), usagePanels) *
((1 + rate / 100) - 1) /
(Math.Pow(1+rate/100, (usagePanels))-1)) * 100;
Thanks to Jason Allen and Grhm who basically figured it out and gave great advice.

function to calculate total sale amount

I have a product that sells in a strange way.
The formula to get the current price is:
total_products_sold * 0.05
I need a function that will return the total sales value, given a total_products_sold value.
This needs to figure out all past pricing, using the above formula.
e.g. if I sold 3 products, the total sales amount is:
1 * 0.5 + 2 * 0.5 + 3 * 0.5 = .30
I can't remember the formula, if its a factorial issue or a exponential type equation.
Formula is
total(N) =
1 * 0.5 + 2 * 0.5 + ... + N * 0.5 =
(1 + 2 + ... + N) * 0.5 = (check this link)
((N + 1) * N / 2) * 0.5
function could be something like
float total (int products) {
return (products + 1) * products / 2 * 0.5;
}

Categories