Click here to Skip to main content
15,897,968 members
Articles / Programming Languages / C++

Optimizing a Function of One Variable

Rate me:
Please Sign up or sign in to vote.
4.94/5 (9 votes)
26 Jun 2014BSD3 min read 64.5K   541   31  
This article presents a method for optimizing a function of one variable without requiring a derivative function.
#include <iostream>
#include <iomanip>
#include "Brent.h"

class foo
{
public:
    double operator()(double x) {return -x*exp(-x);}
};


int main()
{
	foo f;
	double minloc; // location of the minimum
	double minval; // value at the minimum
	std::cout << std::setprecision(7); // display seven decimal places in output

	// First minimize over [-1, 2]
	minval = Minimize<foo>(f, -1, 2, 1e-6, minloc);
	std::cout << "Computed minimum location: " << minloc << "\n"
		      << "Exact value:               " << 1.0    << "\n"
			  << "Computed minimum value:    " << minval << "\n"
			  << "Exact minimum value:       " << f(1.0) << "\n\n";

	// Now minimize over [2, 3]
	minval = Minimize<foo>(f, 2, 3, 1e-6, minloc);
	std::cout << "Computed minimum location: " << minloc << "\n"
		      << "Exact value:               " << 2.0    << "\n"
			  << "Computed minimum value:    " << minval << "\n"
			  << "Exact minimum value:       " << f(2.0) << "\n\n";

	return 0;
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The BSD License


Written By
President John D. Cook Consulting
United States United States
I work in the areas of applied mathematics, data analysis, and data privacy.

Check out my blog or send me a note.

 


Comments and Discussions