title: Calculate bond yield to maturity (YTM) in C++
body: <p>I want to calculate bond's yield to maturity given price using either the bisection or the secant method. I know there's C++ recipes online for this, but I can't figure out what's wrong with my own code. Both methods create an infinite loop. When I tried to step through variables, the yield to maturity iterative solutions keep increasing to 80% and higher.</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;math.h&gt;
  
  using namespace std;
  
  class bond {
  private:
      double principal;
      double coupon;
      double timeToMaturity;
  
  public:
      bond(double principal, double coupon, double timeToMaturity) {
          this-&gt;principal = principal;
          this-&gt;coupon = coupon;
          this-&gt;timeToMaturity = timeToMaturity;
      }
  
      double getprice(double YTM);
      double getytm(double price);
      double getytmsec(double price);
  };
  
  bool isZero(double x)
  {
      if (fabs(x) &lt; 1e-10)
          return true;
      return false;
  }
  
  double bond::getprice(double YTM) {
      double pvPrincipal;
      double pvCoupon;
      double factor = 0;
  
      pvPrincipal = this-&gt;principal / pow(1 + YTM, this-&gt;timeToMaturity);
  
      for (int i = 0; (this-&gt;timeToMaturity - i) &gt; 0; i++) {
          double denom = pow(1 + YTM, this-&gt;timeToMaturity - i);
          factor += 1 / denom;
      }
  
      pvCoupon = this-&gt;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 &lt; 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-&gt;getprice(x1);
      double f2 = this-&gt;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 &lt;&lt; "YTM is " &lt;&lt; myBond.getytm(950) &lt;&lt; endl;
      cout &lt;&lt; "YTM is " &lt;&lt; myBond.getytmsec(950) &lt;&lt; endl;
  
      return 0;
  }
  </code></pre>