| 1 | /* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ |
| 2 | |
| 3 | /* |
| 4 | Copyright (C) 2007 Allen Kuo |
| 5 | |
| 6 | This file is part of QuantLib, a free-software/open-source library |
| 7 | for financial quantitative analysts and developers - http://quantlib.org/ |
| 8 | |
| 9 | QuantLib is free software: you can redistribute it and/or modify it |
| 10 | under the terms of the QuantLib license. You should have received a |
| 11 | copy of the license along with this program; if not, please email |
| 12 | <quantlib-dev@lists.sf.net>. The license is also available online at |
| 13 | <http://quantlib.org/license.shtml>. |
| 14 | |
| 15 | This program is distributed in the hope that it will be useful, but WITHOUT |
| 16 | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS |
| 17 | FOR A PARTICULAR PURPOSE. See the license for more details. |
| 18 | */ |
| 19 | |
| 20 | #include <ql/math/bspline.hpp> |
| 21 | #include <ql/errors.hpp> |
| 22 | |
| 23 | namespace QuantLib { |
| 24 | |
| 25 | BSpline::BSpline(Natural p, |
| 26 | Natural n, |
| 27 | const std::vector<Real>& knots) |
| 28 | : p_(p), n_(n), knots_(knots) { |
| 29 | |
| 30 | QL_REQUIRE(p >= 1, "lowest degree B-spline has p = 1" ); |
| 31 | QL_REQUIRE(n >= 1, "number of control points n+1 >= 2" ); |
| 32 | QL_REQUIRE(p <= n, "must have p <= n" ); |
| 33 | |
| 34 | QL_REQUIRE(knots.size() == p+n+2,"number of knots must equal p+n+2" ); |
| 35 | |
| 36 | for (Size i=0; i<knots.size()-1; ++i) { |
| 37 | QL_REQUIRE(knots[i] <= knots[i+1], |
| 38 | "knots points must be nondecreasing" ); |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | |
| 43 | Real BSpline::operator()(Natural i, Real x) const { |
| 44 | QL_REQUIRE(i <= n_, "i must not be greater than n" ); |
| 45 | return N(i,p: p_,x); |
| 46 | } |
| 47 | |
| 48 | |
| 49 | Real BSpline::N(Natural i, Natural p, Real x) const { |
| 50 | |
| 51 | if (p==0) { |
| 52 | return (knots_[i] <= x && x < knots_[i+1]) ? 1.0 : 0.0; |
| 53 | } else { |
| 54 | return ((x - knots_[i])/(knots_[i+p] - knots_[i]))*N(i,p: p-1,x) + |
| 55 | ((knots_[i+p+1]-x)/(knots_[i+p+1]-knots_[i+1]))* N(i: i+1,p: p-1,x); |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | } |
| 60 | |
| 61 | |