我想使用二分法或割线法计算给定价格的债券到期收益率。我知道网上有 C++ 食谱,但我不知道我自己的代码有什么问题。这两种方法都会创建一个无限循环。当我尝试逐步分析变量时,迭代解决方案的成熟收益率不断增加到 80% 甚至更高。
#include <iostream>
#include <math.h>
using namespace std;
class bond {
private:
double principal;
double coupon;
double timeToMaturity;
public:
bond(double principal, double coupon, double timeToMaturity) {
this->principal = principal;
this->coupon = coupon;
this->timeToMaturity = timeToMaturity;
}
double getprice(double YTM);
double getytm(double price);
double getytmsec(double price);
};
bool isZero(double x)
{
if (fabs(x) < 1e-10)
return true;
return false;
}
double bond::getprice(double YTM) {
double pvPrincipal;
double pvCoupon;
double factor = 0;
pvPrincipal = this->principal / pow(1 + YTM, this->timeToMaturity);
for (int i = 0; (this->timeToMaturity - i) > 0; i++) {
double denom = pow(1 + YTM, this->timeToMaturity - i);
factor += 1 / denom;
}
pvCoupon = this->coupon * factor;
return pvPrincipal + pvCoupon;
}
// Bisection method
double bond::getytm(double price) {
double low = 0;
double high = 1;
double f0 = getprice(low);
double f2 = 1;
double x2 = 0;
while (!isZero(f2)) {
x2 = (low + high) / 2;
f2 = getprice(x2) - price;
if (f2 < 0) {
low = x2;
}
else {
high = x2;
}
}
return x2;
}
// Secant method
double bond::getytmsec(double price) {
double x1 = price;
double x2 = price + 0.25;
double f1 = this->getprice(x1);
double f2 = this->getprice(x2);
for (; !isZero(f1 - price); x2 = x1, x1 = price) {
f1 = getprice(x1);
f2 = getprice(x2);
price = x1 - f1 * (x1 - x2) / (f1 - f2);
}
return price;
}
int main() {
bond myBond = { 1000, 25, 6 };
cout << "YTM is " << myBond.getytm(950) << endl;
cout << "YTM is " << myBond.getytmsec(950) << endl;
return 0;
}