| 1 | /* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ |
| 2 | |
| 3 | /* |
| 4 | Copyright (C) 2007 Mark Joshi |
| 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/quadratic.hpp> |
| 21 | |
| 22 | namespace QuantLib |
| 23 | { |
| 24 | |
| 25 | quadratic::quadratic(Real a, Real b, Real c) : a_(a), b_(b), c_(c) {} |
| 26 | |
| 27 | Real quadratic::turningPoint() const { |
| 28 | return -b_/(2.0*a_); |
| 29 | } |
| 30 | |
| 31 | Real quadratic::valueAtTurningPoint() const { |
| 32 | return (*this)(turningPoint()); |
| 33 | } |
| 34 | |
| 35 | Real quadratic::operator()(Real x) const { |
| 36 | return x*(x*a_+b_)+c_; |
| 37 | } |
| 38 | |
| 39 | Real quadratic::discriminant() const { |
| 40 | return b_*b_-4*a_*c_; |
| 41 | } |
| 42 | |
| 43 | // return false if roots not real, and give turning point instead |
| 44 | bool quadratic::roots(Real& x, Real& y) const { |
| 45 | Real d = discriminant(); |
| 46 | if (d<0) { |
| 47 | x = y = turningPoint(); |
| 48 | return false; |
| 49 | } |
| 50 | d = std::sqrt(x: d); |
| 51 | x = (-b_ - d)/(2*a_); |
| 52 | y = (-b_ + d)/(2*a_); |
| 53 | return true; |
| 54 | |
| 55 | } |
| 56 | } |
| 57 | |