Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cstdlib>
- #include <cmath>
- #include <iostream>
- //QUADRATIC APPROX
- //accuracy is a parameter that tells us when algorithm will stop.
- //If difference between in x after another algorithm step is less than that accuracy algorithm will be stopped
- #define ACCURACY 0.01
- //a is left border of area where we look for answer and b is right
- double a = -1;
- double b = 1;
- //our function in which we are trying to find minimum in range [-1,1]
- double function1(double x){
- double s = sin(2*x+1)+2;
- return 1 / (1 + exp(s));
- }
- double function2(double x){
- return -sin(x+1);
- }
- //this function calculates next x (x2) using quadratic approximation (check lab pdf for more info)
- //it takes as parameters pointer to function we calculate and previous x (x1)
- double qudratApprox(double x1, double(*func)(double)){
- double x2;
- x2 = (func(a)*(pow(b,2) - pow(x1,2)) + func(x1)*(pow(a,2) - pow(b,2)) + func(b)*(pow(x1,2) - pow(a,2)))/
- (func(a)*(b-x1) + func(x1)*(a-b) + func(b)*(x1-a));
- x2 *= 0.5;
- //x2 has to be beetween left and right border otherwise more advanced implementation of the algorithm has to be used
- if(a < x2 && b > x2){
- return x2;
- }else{
- std::cout<< "ERROR HAS OCCURED\n";
- }
- return x2;
- }
- int main(){
- //for the beggining we put x in the middle of our range
- double x = 0;
- //variable for storing next x
- double x2;
- //check internet to find out what is do while loop
- do{
- //first we calculate our next x
- x2 = qudratApprox(x,function1);
- //std::cout << x2 << std::endl;
- //now we are comparing which in which point function is bigger
- //(check lab pdf why we do that, that is the essential of this algorithm)
- if(function1(x) > function1(x2)){
- //this and below if statements are for swiping,
- //we will shrink our range from left or right side depending on what side are x and x2
- if(x < x2) a = x;
- else b = x;
- }else{
- if(x < x2) a = x2;
- else b = x2;
- }
- //again we put our x in the middle of the new shrinken range
- x = (a+b)/2;
- std::cout << "x = " << x << std::endl;
- //we repeat these steps until difference between two steps is smaller than predefined accuracy
- }while(abs(x-x2) >= ACCURACY);
- //finally we print out our result
- std::cout << "xmin = " << x << std::endl;
- std::cout << "f(xmin) = " << function1(x) << std::endl;
- return 1;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement