Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding Local maximum in C

Tags:

c

max

I would like to find the local maximum within the interval of 0 to 3.1416 for this Sin(x) function. But it shows always 0 as the maximum value.i.e The maximum value=0; Please help me finding my faults.

thanks.

#include<stdio.h>
#include<math.h>
#include<stdlib.h>
#ifndef max
    #define max(a,b) ((a)>(b)?(a):(b))
#endif
double f(double x){
return sin(x);
}
double bisection(double a,double b)
{
double Fa=f(a);
double Fb=f(b);
double midpoint=(a+b)/2;
double Fmidpoint=f(midpoint);
while(abs(b-a)>1e-6){
double left=(a+midpoint)/2;
double right=(b+midpoint)/2;
double Fleft=f(left);
double Fright=f(right);
if(midpoint>max(Fleft,Fright)){
    a=left;
    Fa=Fleft;
    b=right;
    Fb=Fright;
}
else{
    if(Fleft>Fright)
    {
        b=midpoint;
        Fb=Fmidpoint;
        midpoint=left;
        Fmidpoint=Fleft;
    }
    else{
        a=midpoint;
        Fa=Fmidpoint;
        midpoint=right;
        Fmidpoint=Fright;
    }
}
}
return midpoint;
}
int main(){
double maximum;
double rangeleft=0;
double rangeright=3.1416;
maximum=bisection(rangeleft,rangeright);
printf("%d",maximum);
return 0;
}
like image 546
Gorge Avatar asked May 31 '11 16:05

Gorge


1 Answers

You have an error in calling the printf function.

You should not use %d format identifier here because it means that printf should output an integer while your maximum variable is double.

Use %f instead and your program will output 1.5708 which is correct.

You can find the list of all possible printf format identifiers on Wikipedia.

like image 86
Yuri Stuken Avatar answered Sep 29 '22 07:09

Yuri Stuken