1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
| #include <stdio.h>
#include <math.h>
float maFonc( float x)
float deriv( float x)
{
return 0.4*x*x*x - x*x + 0.7 ;
}
float newton ( float Fonc( float ), float Deriv(float ), float x0, float eps, float eps2, int MaxIter ){
float d, y0, x1 ; int nbIter=0;
y0=Fonc(x0); d=Deriv(x0);
while( fabs(y0) > eps && nbIter < MaxIter ){
if (fabs(d)<eps2){
printf("\n derive proche de zero: %10.7f \n" , d );
exit (-1);
}
if (y==0) return x1;
x1 -= y0/d;
y0= Fonc(x1);
d=Deriv(x1);
ndIter++;
}
return x;
}
float dichotomie( float Fonc( float ), float a, float b, float eps, int MaxIter ){
float x, y; int nbIter=0;
x=(a+b)/2; y=Fonc(x);
while( fabs(y) > eps && nbIter < MaxIter ){
if (y==0) return x;
if (y * Fonc(a)< 0) b= x;
else a=x;
x=(a+b)/2; y=Fonc(x);
nbIter++;
}
return x;
}
float secante(float Fonc(float ), float x0, float g, float eps, int MaxIter ){
float tmp, y0,y1, x1=g; int nbIter=0;
y0=Fonc(x0); y1=Fonc(x1);
while (fabs(y1-y0) > eps && nbIter < MaxIter ){
tmp=x1;
x1 -= y1 *(x1-x0) / (y1-y0);
x0=tmp; y0=Fonc(x0);
y1 = Fonc(x1);
if (y1 == 0) return x1;
nbIter++;
}
return x1;
}
int main(){
int i; float x, g, d, psi, x_init, xd, xs, xn, psi2;
printf("\n\t\tComparaison des methodes \n");
printf("\nIntervalle et Precision : ");
scanf("%f%f%f", &g, &d,&psi);
if (maFonc(g)* maFonc(d) >0) {
printf("\nEquation n'a peut etre pas de solution\n"); return -1;
}
x_init=(g+d)/2;
printf("Nbre Iter Dichotomie Secante newton");
for ( i=2; i < 15; i++){
xd=dichotomie(maFonc,g,d,psi, i);
xs=secante(maFonc,x_init,d,psi, i);
xn=newton(maFonc, deriv , x_init, psi, psi2, i);
printf("\n %7d %10.7f %10.7f" , i, xd , xs ,xn);
}
putchar('\n'); return 0;
} |
Partager