Skip to content

Instantly share code, notes, and snippets.

@andr1972
Created October 25, 2016 20:48
Show Gist options
  • Save andr1972/fd0c3a610d6e4defc408974c50cff070 to your computer and use it in GitHub Desktop.
Save andr1972/fd0c3a610d6e4defc408974c50cff070 to your computer and use it in GitHub Desktop.
#define _USE_MATH_DEFINES
#include <float.h>
#include <math.h>
#include <stdio.h>
#include <assert.h>
double f(double x)
{
return sin(x);
}
double GoldenRatioMinima(double a, double b, double tol)
{
const double k = (sqrt(5) - 1) / 2;
double c = b - k * (b - a);
double fc = f(c);
double d = a + k * (b - a);
double fd = f(d);
double eps = tol + fabs(b)*DBL_EPSILON;
while ((b - a) > eps)
{
if (fc < fd)
{
// choose interval [a, d]
b = d;
d = c;
fd = fc;
c = b - k * (b - a);
fc = f(c);
}
else
{
// choose interval [c, b]
a = c;
c = d;
fc = fd;
d = a + k * (b - a);
fd = f(d);
}
eps = tol + fabs(b)*DBL_EPSILON;
}
return (a + b) / 2;
}
int main()
{
double res = GoldenRatioMinima(4.7, 4.8, 1e-16);
printf("min in %.16f\n", res);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment