So this project is a little outside of my comfort zone. I would describe my current stage of development as being one in which, “I know about things like: collection, design patters, and in general what makes for good OOP. But these things are sort of at my current limits. And so I probably don’t use them or attempt to use them as much as I should.”
I’m trying to change that, so I've been working on fairly small challenge/application that really lends itself to the above and asking myself to write smart, clean code. I’m fairly happy with what I've been able to do so far. However, I have two classes remaining that I still need to dive into. I have a lot of ideas about how to go about this. I’m sure some are good and some are bad, but more than anything, I think I’m over thinking things.
In short, here is what I’m trying to do, here is what I have, and here is where I need to go:
What I’m trying to do: The simplest way to state the goals for this app are, I have credit card (this class is the class I have done), I have wallets, and I have people. Looking at it from a high-level perspective, I’m putting cards in the wallets and wallets in the people. I have 3 cards, they really only differ in their ‘names’ and interest rates. I want some wallets to have 1 card and for others to have all three. As for wallets clearly every person needs at least one, but I’d like to give someone two. And that is really about it, I worked out some math for simple interest on the card which I’ll tie in at some point, but mostly I’m looking to build a clean and well-designed app.
What I have: As I've stated I more or less have the CreditCard class done. I’m still fine tuning it, but I've been able to improve it a lot and I’m casually happy with it. I’ll include this class below to provide context for the app and also, so you can provide suggestions if needed. At the top of the class you’ll see a lot of documentation. This is mostly just the math, and it’s logic, for working out simple interest. You’ll see. But I also have two test cases that I’m coding to, you’ll see this too.
Where I need to go: Well I have credit cards. Now I just need wallets and people. From my perspective, I could see the wallet making use of an ArrayList. Though, it could be the case that a different aspect of collections might serve better. I have mostly(mostly) used ArrayList, and so I keep mostly using ArrayList. It’s worked out so far… Beyond that, I have been considering making Wallet and Person abstract, which seems like a good idea, but once again, not much experience in making these choices.
So at the end of all of this, I’m look for some direction, conformation of good ideas and alternatives to weaker ones. If these could be combine with examples or if suggestions could express themselves in both words and code, this would be optimal because I get a lot more out of advice when I can see it in action. For me an OK suggestion with code, is ‘generally’ more helpful than a great suggestion without. It’s all about being able to apply that advice. But, that’s just me and everyone is different. What I can tell you, that is definite, is that all suggestion, whatever they are, will be appreciated and helpful. Because, I’m doing this, I’m here, to learn.
/*
* Test Cases:
* 1) 1 person has 1 wallet and 3 cards (1 Visa, 1 MC 1 Discover) – Each Card has a balance of $100 – calculate the total interest (simple interest) for this person and per card.
*
* 2) 1 person has 2 wallets Wallet 1 has a Visa and Discover , wallet 2 a MC - each card has $100
* balance - calculate the total interest(simple interest) for this person and interest per wallet
*/
/*
* Formula Key:
*
* Algebraic Symbols:
* A = Total Accrued Amount (principal + interest)
* P = Principal Amount
* I = Interest Amount
* r & R = Rate of Interest per year in percentage & decimal
* t = Time Period involved in months or years(duration pertaining to this equation)
*
* Rate of Interest, Percentage To Decimal Equations:
* R = r * 100
* r = R / 100
*
* Simple Interest Equation:
* A = P(1 + (r * t))
*/
/*
* Card:
* VISA 10%
*
* Equation:
* Accrued Amount(A) = Principle Amount(P) * (1 +(Interest Rate(r) * Time Period(t)))
*
* Calculation:
* First, converting Interest Rate(R) of 10%, to, Interest Rate(r) of 0.1
* r = R/100 = 10%/100 = 0.1 per year,
* put Time Period(t) of 1 month into years,
* months/year(1 month ÷ 12) = 0.08 years
*
* Solving Equation:
* A = 100(1 + (0.1 × 0.08)) = 100.8
* A = $ 100.80
*
* Solution:
* The total Amount Accrued(A), Principal(P) plus Interest(I),
* from Simple Interest on a Principal(P) of $ 100.00
* at a Rate(r = R/100(convert a percentage to a decimal)) of 10% or 0.1 per year
* for 0.08 years, 1 month(t) is $ 100.80.
*/
/*
* Card:
* MC(Master Card) 5%
*
* Equation:
* Accrued Amount(A) = Principle Amount(P) * (1 +(Interest Rate(r) * Time Period(t)))
*
* Calculation:
* First, converting Interest Rate(R) of 5%, to, Interest Rate(r) of 0.05
* r = R/100 = 5%/100 = 0.05 per year,
* put Time Period(t) of 1 month into years,
* months/year(1 month ÷ 12) = 0.08 years
*
* Solving Equation:
* A = 100(1 + (0.05 × 0.08)) = 100.4
* A = $ 100.40
*
* Solution:
* The total Amount Accrued(A), Principal(P) plus Interest(I),
* from Simple Interest on a Principal(P) of $ 100.00
* at a Rate(r = R/100(convert a percentage to a decimal)) of 5% or 0.05 per year
* for 0.08 years, 1 month(t) is $ 100.40.
*/
/*
* Card:
* Discover 1%
*
* Equation:
* Accrued Amount(A) = Principle Amount(P) * (1 +(Interest Rate(r) * Time Period(t)))
*
* Calculation:
* First, converting Interest Rate(R) of 1%, to, Interest Rate(r) of 0.01
* r = R/100 = 1%/100 = 0.01 per year,
* put Time Period(t) into years,
* months/year(1 month ÷ 12) = 0.08 years
*
*
* Solving Equation:
* A = 100(1 + (0.01 × 0.08)) = 100.08
* A = $ 100.08
*
* Solution:
* The total Amount Accrued(A), Principal(P) Plus Interest(I),
* from Simple Interest on a Principal(P) of $ 100.00
* at a Rate(r = R/100(convert a percentage to a decimal)) of 1% or 0.01 per year
* for 0.08 years, 1 month(t) is $ 100.08.
*/
public class CreditCard
{
private BrandOfCard brandOfCard;
private static final double PRINCIPAL_AMOUNT = 100.00;
private static final double TIME_PERIOD = 0.08;
public CreditCard(BrandOfCard brandOfCard)
{
this.brandOfCard = brandOfCard;
}
/*
* A = P(1 + (r * t))
*/
public double getAccruedAmount()
{
double accruedAmount;
accruedAmount = PRINCIPAL_AMOUNT * (1 + (brandOfCard.getInterestRate() * TIME_PERIOD));
return accruedAmount;
}
public enum BrandOfCard
{
VISA(0.1), MASTER_CARD(0.05), DISCOVER(0.01);
private final double interestRate;
BrandOfCard(double interestRate)
{
this.interestRate = interestRate;
}
public double getInterestRate()
{
return interestRate;
}
}
//bottom of class
public static void main(String[] args)
{
CreditCard visa = new CreditCard(BrandOfCard.VISA);
CreditCard masterCard = new CreditCard(BrandOfCard.MASTER_CARD);
CreditCard discover = new CreditCard(BrandOfCard.DISCOVER);
double accruedAmount;
accruedAmount = visa.getAccruedAmount();
System.out.println("Visa card, with a principle amount of $100.00, & an interest rate of 10%, " +
"has accrued $" + (accruedAmount - PRINCIPAL_AMOUNT) + " in interest, " +
"over the last monthly term.");
System.out.println("The total amount due on this card is now $" + accruedAmount);
accruedAmount = masterCard.getAccruedAmount();
System.out.println("Master Card card, with a principle amount of $100.00, & an interest rate of 5%, " +
"has accrued $" + (accruedAmount - PRINCIPAL_AMOUNT) + " in interest, " +
"over the last monthly term.");
System.out.println("The total amount due on this card is now $" + accruedAmount);
accruedAmount = discover.getAccruedAmount();
System.out.println("Discover card, with a principle amount of $100.00, & an interest rate of 1%, " +
"has accrued $" + (accruedAmount - PRINCIPAL_AMOUNT) + " in interest, " +
"over the last monthly term.");
System.out.println("The total amount due on this card is now $" + accruedAmount);
}
}
First of all don't go object happy! More objects != better code!
Look at this from a data perspective because that is where most OOP programmers lose their way. This stuff is stored relationally for a reason.
People make that an object
Wallet - This is simply a middle key to join n number of cards to a person.
CC make that an object since each CC has defined terms of payment, fees, interest rates, etc.
What you end up with is:
Table of users.
Table of cards.
The wallet, unless you want to assign particular attributes to it is really a non existent thing, since having the card owner Key in the CC record links cards to owners.
The rub is really applying payments. Just like the bank adds your deposits to your account before they start processing your checks or auto payments, you have to apply any posted payments before you calc the interest + fees value to add to the balance so:
for owners{
for cards with card.ownerID = owners.ID{
card.balance=card.balance-payments ;
card.balance=card.balance+calcInterest(card.balance, card.rate)+GetSumOfFees(card);
}
}
That is the basic batch job that every CC Issuer runs every night.
On the charging side of things it is the smallest code they can get away with sine this has to happen practically instantaneously at a pay terminal, etc. etc.
public static String chargeThis(String CCData, Double AMT){
CCNum = GetCCNum(CCData) ;
boolean isValid = validateCC(ccData);
if(isValid) return chargeCC(ccNum,AMT) else return rejectedTrans ;
}
About lists hash maps, etc in Java or vectors in C++...
ANY operation on those that sizes them will be blazingly fast right up until the point they exceed the size of the L2 cache! After they exceed the size of L2 cache they get stored in system RAM and their performance goes into the tank. At this point a linked list is superior, since adding or subtracting an element is simply inserting a node, or deleting a node.
Remember, getting advanced performance requires understanding the machine AND understanding how the JVM or compiler arranges things. In order from best to worst storage is as follows:
L0 cache - 1 cpu cycle
L1 cache - 2 cpu cycles
L2 cache - 5 to 10 cpu cycles
System Memory 1000's of cpu cycles
Ethernet ( getting data across the wire ) 10's of K cycles
Disk - 50 to 100 K cycles
Related
so I am designing a football based game in Java where two teams will face off. Then I want to design an algorithm to calculate the probability of team A or team B winning depending on some factors.
The strength of the team (which doesn't change after being set)
The form the team is in (how many of their last 5 games they won or lost)
Some randomness so it can go either way even if team A is much stronger and in better form than team B.
I don't really know where to start though, any tips would be appreciated!
Let's start with a bit of OOP:
public class Team{
private double /*int*/ strength;//Change the datatype, by your favors
private double formOfLastFiveMatches;//0 for lost all, 1 for won all, 0.6 for won 3 of 5
private Random random; //For the randomness
//...Constructors, Getters,Setters
}
This is models your team.
Now start with calculating the match.
public class SoccerSimulator{
private Team a,b;
//...Constructors, Getters,Setters
/**
* Calculate the probability, that A wins.
* #return the probability, A wins.
*/
public double calculateProbability(){
double strengthA = a.getStrength();
double strengthB = b.getStrength();
if(a.getForm() <= 0.2)
strengthA *= (1 + (Math.random % 0.1));//Up to 10% bonus, because they won only 0-1 games in the last 5 games
if(b.getForm() <= 0.2)
strengthB *= (1 + (Math.random % 0.1));
//Do something with the random number generator
//....
//TODO: Better algorithm
double sum=strengthA + strengthB;
return strengthA / sum;//Get the fraction A has in relationship to the sum.
}
}
This is an quite basic algorithm, but you can use it as a starting point.
Background: I'm writing some geometry software in Java. I need the precision offered by Java's BigDecimal class. Since BigDecimal doesn't have support for trig functions, I thought I'd take a look at how Java implements the standard Math library methods and write my own version with BigDecimal support.
Reading this JavaDoc, I learned that Java uses algorithms "from the well-known network library netlib as the package "Freely Distributable Math Library," fdlibm. These algorithms, which are written in the C programming language, are then to be understood as executed with all floating-point operations following the rules of Java floating-point arithmetic."
My Question: I looked up fblibm's sin function, k_sin.c, and it looks like they use a Taylor series of order 13 to approximate sine (edit - njuffa commented that fdlibm uses a minimax polynomial approximation). The code defines the coefficients of the polynomial as S1 through S6. I decided to check the values of these coefficients, and found that S6 is only correct to one significant digit! I would expect it to be 1/(13!), which Windows Calculator and Google Calc tell me is 1.6059044...e-10, not 1.58969099521155010221e-10 (which is the value for S6 in the code). Even S5 differs in the fifth digit from 1/(11!). Can someone explain this discrepancy? Specifically, how are those coefficients (S1 through S6) determined?
/* #(#)k_sin.c 1.3 95/01/18 */
/*
* ====================================================
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunSoft, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*/
/* __kernel_sin( x, y, iy)
* kernel sin function on [-pi/4, pi/4], pi/4 ~ 0.7854
* Input x is assumed to be bounded by ~pi/4 in magnitude.
* Input y is the tail of x.
* Input iy indicates whether y is 0. (if iy=0, y assume to be 0).
*
* Algorithm
* 1. Since sin(-x) = -sin(x), we need only to consider positive x.
* 2. if x < 2^-27 (hx<0x3e400000 0), return x with inexact if x!=0.
* 3. sin(x) is approximated by a polynomial of degree 13 on
* [0,pi/4]
* 3 13
* sin(x) ~ x + S1*x + ... + S6*x
* where
*
* |sin(x) 2 4 6 8 10 12 | -58
* |----- - (1+S1*x +S2*x +S3*x +S4*x +S5*x +S6*x )| <= 2
* | x |
*
* 4. sin(x+y) = sin(x) + sin'(x')*y
* ~ sin(x) + (1-x*x/2)*y
* For better accuracy, let
* 3 2 2 2 2
* r = x *(S2+x *(S3+x *(S4+x *(S5+x *S6))))
* then 3 2
* sin(x) = x + (S1*x + (x *(r-y/2)+y))
*/
#include "fdlibm.h"
#ifdef __STDC__
static const double
#else
static double
#endif
half = 5.00000000000000000000e-01, /* 0x3FE00000, 0x00000000 */
S1 = -1.66666666666666324348e-01, /* 0xBFC55555, 0x55555549 */
S2 = 8.33333333332248946124e-03, /* 0x3F811111, 0x1110F8A6 */
S3 = -1.98412698298579493134e-04, /* 0xBF2A01A0, 0x19C161D5 */
S4 = 2.75573137070700676789e-06, /* 0x3EC71DE3, 0x57B1FE7D */
S5 = -2.50507602534068634195e-08, /* 0xBE5AE5E6, 0x8A2B9CEB */
S6 = 1.58969099521155010221e-10; /* 0x3DE5D93A, 0x5ACFD57C */
#ifdef __STDC__
double __kernel_sin(double x, double y, int iy)
#else
double __kernel_sin(x, y, iy)
double x,y; int iy; /* iy=0 if y is zero */
#endif
{
double z,r,v;
int ix;
ix = __HI(x)&0x7fffffff; /* high word of x */
if(ix<0x3e400000) /* |x| < 2**-27 */
{if((int)x==0) return x;} /* generate inexact */
z = x*x;
v = z*x;
r = S2+z*(S3+z*(S4+z*(S5+z*S6)));
if(iy==0) return x+v*(S1+z*r);
else return x-((z*(half*y-v*r)-y)-v*S1);
}
We can use trig identities to get everything down to 0≤x≤π/4, and then need a way to approximate sin x on that interval. On 0≤x≤2-27, we can just stick with sin x≈x (which the Taylor polynomial would also give, within the tolerance of a double).
The reason for not using a Taylor polynomial is in step 3 of the algorithm's comment. The Taylor polynomial gives (provable) accuracy near zero at the expense of less accuracy as you get away from zero. By the time you get to π/4, the 13th order Taylor polynomial (divided by x) differs from (sin x)/x by 3e-14. This is far worse than fblibm’s error of 2-58. In order to get that accurate with a Taylor polynomial, you’d need to go until (π/4)n-1/n! < 2-58, which takes another 2 or 3 terms.
So why does fblibm settle for an accuracy of 2-58? Because that’s past the tolerance of a double (which only has 52 bits in its mantissa).
In your case though, you’re wanting arbitrarily many bits of sin x. To use fblibm’s approach, you’d need to recalculate the coefficients whenever your desired accuracy changes. Your best approach seems to be to stick with the Taylor polynomial at 0, since it’s very easily computable, and take terms until (π/4)n-1/n! meets your desired accuracy.
njuffa had a useful idea of using identities to further restrict your domain. For example, sin(x) = 3*sin(x/3) - 4*sin^3(x/3). Using this would let you restrict your domain to 0≤x≤π/12. And you could use it twice to restrict your domain to 0≤x≤π/36. This would make it so that your Taylor expansion would have your desired accuracy much more quickly. And instead of trying to get an arbitrarily accurate value of π for (π/4)n-1/n!, I’d recommend rounding π up to 4 and going until 1/n! meets your desired accuracy (or 3-n/n! or 9-n/n! if you’ve used the trig identity once or twice).
I'm trying to calculate the future investment amount in Java.
My program runs, but it's not giving me the correct answer.
If the
investmentAmount is 1000.56,
interest rate is 4.25, and
number of years is 1,
the answer should be $1043.92.
The formula we have to use is futureInvestmentValue = investmentAmount * (1 + monthlyInterestRate) ^ numberOfYears * 12
Below is my class
// Import Java Scanner
import java.util.Scanner;
public class Ex_2_21 {
public static void main(String[] args) {
//Create a Scanner object
Scanner input = new Scanner(System.in);
//Prompt the user to enter investment amount, annual interest rate, and number of years
System.out.println("Enter investment amount:");
System.out.println("Enter annual interest rate:");
System.out.println("Enter number of years:");
float investmentamount = input.nextFloat();
float interestrate = input.nextFloat();
float numberofyears = input.nextFloat();
float years = numberofyears * 12;
//Formula to calculate the accumulated value
float futureInvestmentValue = (float) (investmentamount * Math.pow((years), 1 + interestrate));
//Print result
System.out.println("The accumulated value is " + futureInvestmentValue);
}
}
On top of what #Luiggi said, did you consider that if it is 4.25 interest rate, that is 425% interest rate, what you want is 1 + 0.0425
You're using years (equal to years * 12) when you mean months, and you're not using monthly interest rate at all. Divide annual interest rate (as entered) by 12 to get monthly interest rate (and also make sure it's a fraction, not a bare percentage, so if they're entering 4.25 it needs to be divided by 100 to get .0425), and introduce a new variable for total month duration. Then (as Luiggi notes) swap the argument order.
float futureInvestmentValue = (float) (investmentAmount * Math.pow(1 + monthlyInterestRate, months));
Here's the problem:
Math.pow((years), 1 + interestrate)
It should be
Math.pow(1 + interestrate, years)
As noted in Math#pow(double a, double b):
Parameters:
a - the base
b - the exponent
Returns
The value ab
There are two problems in the above given Java program:
Lack of problem understanding (kindly, take this suggestion in a positive interest. If we, understand the problem correctly, we are very much near to its correct programming solution.)
Formula for future investment value (A) is as follows:
a) Compounded annually:
A = P*(1+R)^N
Where, A = Future value, P = Original amount invested, R = Interest rate (given as %, in calculation use as R/100), N = Time period for which compound interest rate is applied (in years)
b) Compounded monthly:
A = P*(1+(R/12))^(N*12)
Where, A = Future value, P = Original amount invested, R = Monthly interest rate (given as %, in calculation use as R/100, it is not annual interest rate), N = Time period for which compound interest rate is applied (in years)
As per values of given sample problem, we find in order to calculate future investment value, we should be using formula (b).
So, w.r.t above given Java program, to incorporate this correction we need to simply add one more statement after the interestrate variable declaration line:
interestrate = interestrate / (100 * 12);
Second problem is lack of understanding of Java programming language constructs / logical error by ignorance. Whatever is the case; it does not matter. Technically, it is a programming error and thus it needs rectification.
As already suggested above by Luiggi Mendoza, in Java programming language if we want to express mathematical expression A^B then we have to use java.lang.Math.pow() method with following syntax:
public static double pow(double A, double B)
So, again w.r.t above given Java program, to incorporate this second correction we have to simply correct the line which declares the futureInvestmentValue variable and using the Math.pow() method; as follows:
float futureInvestmentValue = (float) (investmentamount * Math.pow(1 + interestrate, years));
Incorporating these two corrections, we make our solution correct. Based on the principle of GIGO (Garbage In Garbage Out, Gold In Gold Out) we will definitely get correct and exact answer to our any sample problem given values; as expected.
Happy Programming.
The formula that I want to convert in java is
Over limit Cash Deposit Fee = [(Input $ cash deposit) – ($ Cash deposits included in plan)] / 1000 * (price/each extra $1000 deposited)
The code that I am writing is
int inputCash = 50;
int cashDepsitFromPlan = 40;
int cashDepositOverLimitFee = 2.5;
cashDepositOverLimit = (double) ((inputCash -cashDepsitFromPlan) / 1000) * ???;
how do I find ???(price/each extra $1000 deposited)
If you're working with floating point numbers, you may want to reconsider the use of the int data type.
This, for a start, is going to cause all sorts of grief:
int cashDepositOverLimitFee = 2.5;
You're better off using double for everything.
In terms of finding the unknown variable here, that's something specific to your business rules, which aren't shown here.
I'd hazard a guess that the price/$1000 figure is intimately related to your cashDepositOverLimitFee variable such as it being $2.50 for every extra $1000.
That would make the equation:
inputCash - cashDepsitFromPlan
cashDepositOverLimit = ------------------------------ * cashDepositOverLimitFee
1000
which makes sense. The first term on the right hand side is the number of excess $1000 lots you've deposited over and above the plan. You would multiply that by a fee rate (like $2.50 or 2.5%) to get the actual fee.
However, as stated, we can't tell whether it's $2.50 or 2.5% based on what we've seen. You'll have to go back to the business to be certain.
You have to algebraically manipulate the equation to solve for that.
cashDepositOverLimitFee = (double) ((inputCash -cashDepsitFromPlan) / 1000) * ???
cashDepositOverLimitFee*1000 = (double) (inputCash -cashDepsitFromPlan) * ???
(cashDepositOverLimitFee*1000) / (double) (inputCash -cashDepsitFromPlan) = ???
??? = (cashDepositOverLimitFee*1000) / (double) (inputCash -cashDepsitFromPlan)
Note that the (double) cast must remain in order to ensure a floating point result.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
Was wondering if anyone can point me to an open source java quant library that provides implementation for Excel Price and Yield functions.
Thanks,
Tapasvi
The Excel PRICE function is a simple sum of discounted cash flows, discounted assuming a flat zero rate discounting curve. It is documented here: Excel Help / PRICE.
I wrote a small Java version of the function, which I am posting below. The Java version just takes a "time to maturity" and does not support different daycountings, while the Excel PRICE function takes a settlement date and maturity date and supports different daycountings. However, you can attribute for the different daycountings by converting the coupon. Note also that the Excel function has a strange hardcoded notional of 100 in front of the coupon.
An Excel sheet benchmarking the two implementations can be downloaded here. The sheet requires "Obba".
The Excel YIELD function is just a Newton solver applied to the PRICE function, see Excel Help / YIELD. A Java implementation of the Newton solver can be found at finmath.net.
/*
* Created on 07.04.2012
*/
/**
* This class implements some functions as static class methods.
*
* (c) Copyright 2012 Christian Fries.
*
* #author Christian Fries
* #version 1.0
*/
public class SpreadsheetFunctions {
/**
* Re-implementation of the Excel PRICE function (a rather primitive bond price formula).
* The reimplementation is not exact, because this function does not consider daycount conventions.
* We assume we have (int)timeToMaturity/frequency future periods and the running period has
* an accrual period of timeToMaturity - frequency * ((int)timeToMaturity/frequency).
*
* #param timeToMaturity The time to maturity.
* #param coupon Coupon payment.
* #param yield Yield (discount factor, using frequency: 1/(1 + yield/frequency).
* #param redemption Redemption (notional repayment).
* #param frequency Frequency (1,2,4).
* #return price Clean price.
*/
public static double price(
double timeToMaturity,
double coupon,
double yield,
double redemption,
int frequency)
{
double price = 0.0;
if(timeToMaturity > 0) {
price += redemption;
}
double paymentTime = timeToMaturity;
while(paymentTime > 0) {
price += coupon/frequency;
// Discount back
price = price / (1.0 + yield / frequency);
paymentTime -= 1.0 / frequency;
}
// Accrue running period
double accrualPeriod = 0.0-paymentTime; // amount of running period which lies in the past (before settlement)
price *= Math.pow(1.0 + yield / frequency, accrualPeriod*frequency);
price -= coupon/frequency * accrualPeriod*frequency;
return price;
}
}
You may want to have a look at QuantLib. It's a free/open source library for quantitative finance.