-2

I am doing a TVM project and not quite understand how the compound interest translates into code. I am using BA II Plus financial calculator as a reference.

Example: Find the future value of $100 payments made at the beginning of every month for 10 years if interest is 5% compounded quarterly.

In the financial calculator:

N: 120 (10y x 12m)

I/Y: 5% (annually interest rate)

P/Y: 12 (12 times per year)

C/Y: 4 (4 times per year)

PV: 0

PMT: 100

BGN: TRUE

FV: [CPT] [FV] => -15575.41334


Here is the future value method.

static public double fv(double r, int n, double pmt, double pv, int bgn) {
    return -(pv * Math.pow(1 + r, n) + pmt * (1 + r * bgn) * (Math.pow(1 + r, n) - 1) / r);
}

Call the method using numbers from the example

//             rate     n    pmt  pv bgn
double fv = fv(0.05/12, 120, 100, 0, 1); // -15592.928894335751 which is wrong
Saran
  • 443
  • 1
  • 7
  • 17

1 Answers1

1

It seems you are getting numerical errors in the computation.

Floating-point computations are inherently subject to rounding errors, and these can add up and become very large.

E.g. general background (long read):

https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html

You can try using a high-precision computation library.

E.g. some good options are mentioned in this answer:

https://stackoverflow.com/a/284588/9549171

edit: you could try to analyse the expression you are using with https://herbie.uwplse.org/ (but the web version times out on your expression, you'll have to download their software)

sesquipedalias
  • 183
  • 2
  • 10
  • Thanks for your answer, the compound interest (C/Y = 4) is not yet in my params. I do not know where to put it yet. and that's where I am stuck right now. – Saran Apr 03 '19 at 17:48
  • I haven't been thinking about *what* you are trying to calculate at all. I just see you taking a non-trivial formula and writing it out directly in java code and that instantly makes me suspicious. Rounding errors can be tricky and dangerous. For example, doing so with the standard quadratic formula is famously dangerous (an explanation can be found in https://homes.cs.washington.edu/~jrw12/herbie.pdf) [edit: nothing wrong with java in particular, though] – sesquipedalias Apr 03 '19 at 17:54