Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <math.h>
- FILE *logfile;
- FILE *logfile2;
- double func1(double x);
- double grid_search(double f(double), double start, double end, double tol);
- double dihotomie(double f(double), double start, double end, double tol);
- double raportAur(double f(double), double start, double end, double tol);
- int main()
- {
- logfile = fopen("log.csv","w");
- logfile2 = fopen("log2.csv", "w");
- if(logfile == NULL) return 1;
- double op = grid_search( func1, 0, 2*acos(-1), 0.001);
- double op2 = dihotomie( func1, 0, 2*acos(-1), 0.001);
- double op3 = raportAur( func1, 0, 2*acos(-1), 0.001);
- printf("Optimum: %f ,%f \n", op, func1(op));
- printf("Optimum: %f ,%f \n", op2, func1(op2));
- printf("Optimum: %f ,%f \n", op3, func1(op2));
- return 0;
- }
- double grid_search(double f(double), double start, double end, double tol)
- {
- double min = 32000;
- double i;
- double poz;
- for(i = start ; i < end ; i+=tol)
- {
- fprintf(logfile, "%f , %f , %f , %f \n", i, f(i), poz ,min);
- if(f(i) < min)
- {
- min = f(i);
- poz = i;
- }
- }
- return poz;
- }
- double dihotomie(double f(double), double start, double end, double tol)
- {
- //a = start , b = end
- double eps = tol/3;
- while(end - start > tol)
- {
- double c = ((start + end)/2) - eps;
- double d = ((start + end)/2) + eps;
- if(f(c) > f(d))
- start = c;
- else
- end = d;
- fprintf(logfile2, "%f , %f , %f , %f \n", start, f(start), end ,f(end));
- }
- return start;
- }
- double raportAur(double f(double), double start, double end, double tol)
- {
- double R = ((1+sqrt(5))/2);
- double a = start;
- double b = end;
- double c = b - ((b-a)/R);
- double d = a + ((b-a)/R);
- while(b-a > tol)
- {
- if(f(c) > f(d))
- {
- a = c;
- c = d;
- d = a + (b-a)/R;
- }
- else
- {
- b = d;
- d = c;
- c = b - (b-a)/R;
- }
- }
- return b;
- }
- double vertex(double f(double), double x1, double x2, double x3)
- {
- double y1 = f(x1), y2 = f(x2), y3 = f(x3);
- double denom = (x1-x2)*(x1-x3)*(x2-x3);
- double A = (x3*(y2-y1)+x2*(y1-y3)+x1*(y3-y2))/denom;
- double B = (x3*x3*(y1-y2)+x2*x2*(y1-y3)+x1*x1*(y2-y3))/denom;
- return -B/(2*A);
- }
- double interpolareParabolica(double f(double), double start, double end, double tol)
- {
- double a = start;
- double b = end;
- double c = (a+b)/2;
- while(b-a > tol)
- {
- double d = vertex(f, a , b, c);
- if(d < c)
- {
- double aux;
- aux = c;
- c = d;
- d = aux;
- }
- if(f(c) > f(d))
- {
- a = c;
- c = d;
- }
- else
- {
- b = d;
- }
- }
- }
- double func1(double x)
- {
- return sin(x);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement