Main Page | Namespace List | Class Hierarchy | Alphabetical List | Class List | Directories | File List | Namespace Members | Class Members | File Members

solve.h

Go to the documentation of this file.
00001 // solve.h
00002 // 
00003 // Copyright (C) 2001, Chris Laurel <claurel@shatters.net>
00004 //
00005 // This program is free software; you can redistribute it and/or
00006 // modify it under the terms of the GNU General Public License
00007 // as published by the Free Software Foundation; either version 2
00008 // of the License, or (at your option) any later version.
00009 
00010 #include <utility>
00011 
00012 
00013 // Solve a function using the bisection method.  Returns a pair
00014 // with the solution as the first element and the error as the second.
00015 template<class T, class F> std::pair<T, T> solve_bisection(F f,
00016                                                            T lower, T upper,
00017                                                            T err,
00018                                                            int maxIter = 100)
00019 {
00020     T x = 0.0;
00021 
00022     for (int i = 0; i < maxIter; i++)
00023     {
00024         x = (lower + upper) * (T) 0.5;
00025         if (upper - lower < 2 * err)
00026             break;
00027 
00028         T y = f(x);
00029         if (y < 0)
00030             lower = x;
00031         else
00032             upper = x;
00033     }
00034 
00035     return std::make_pair(x, (upper - lower) / 2);
00036 }
00037 
00038 
00039 // Solve using iteration; terminate when error is below err or the maximum
00040 // number of iterations is reached.
00041 template<class T, class F> std::pair<T, T> solve_iteration(F f,
00042                                                            T x0,
00043                                                            T err,
00044                                                            int maxIter = 100)
00045 {
00046     T x = 0;
00047     T x2 = x0;
00048 
00049     for (int i = 0; i < maxIter; i++)
00050     {
00051         x = x2;
00052         x2 = f(x);
00053         if (abs(x2 - x) < err)
00054             return std::make_pair(x2, x2 - x);
00055     }
00056 
00057     return std::make_pair(x2, x2 - x);
00058 }
00059 
00060 
00061 // Solve using iteration method and a fixed number of steps.
00062 template<class T, class F> std::pair<T, T> solve_iteration_fixed(F f,
00063                                                                  T x0,
00064                                                                  int maxIter)
00065 {
00066     T x = 0;
00067     T x2 = x0;
00068 
00069     for (int i = 0; i < maxIter; i++)
00070     {
00071         x = x2;
00072         x2 = f(x);
00073     }
00074 
00075     return std::make_pair(x2, x2 - x);
00076 }

Generated on Sat Jan 14 22:30:32 2006 for Celestia by  doxygen 1.4.1