/*
 * x-e^-x.c
 *
 * Copyright (C) 2008 - Gimmy, Gianmarco Brocchi
 *
 * This is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with ; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, 
 * Boston, MA  02110-1301  USA
 */
 
 /* Determina lo zero della funzione f(x)= x-1/e^x */

#include <stdio.h>
#include <math.h>

#define ZERO 0.001
#define e 2.71828183

double elevamento_potenza(double base, int potenza)
{
   double valore_ritorno = 1.0;
   int i;
   for(i=0; i<potenza; i++)
   {
      valore_ritorno *= base;
   }
   return(valore_ritorno);
}

main()
{
	float a, b, m;
	float fa, fb ,fm;
	char x;
	int i=0;
	int stampa_dati, iterazioni;
	
	printf("\nProgramma che calcola lo zero della funzione f(x)= x-1/e^x in un intervallo [a;b] dato.");

	/*controllo a b*/
	do {
		printf("\n\nScegliere l'intervallo [a;b]...");
		printf("\nInserire a: ");
		scanf("%f", &a);
		printf("Inserire b: ");
		scanf("%f", &b);
		fa = a-1/elevamento_potenza(e, a);
		fb = b-1/elevamento_potenza(e, b);
		if (fa*fb>0)
			printf("\nIn questo intervallo la funzione non interseca l'asse x. Riprovare.");
	}
	while(fa*fb>0);
	
	/*richiesta stampo dati e iterazioni*/
	do
	{
		stampa_dati= -1;
		printf("\nVisualizzare i dati?(1 per Sì, 0 per No) ");
		scanf("%d", &stampa_dati);
	} 
	while (stampa_dati!=0 && stampa_dati!=1);
	
	do
	{
		iterazioni= 0;
		printf("\nQuante iterazioni vuoi fare al massimo? ");
		scanf("%d", &iterazioni);
		if (iterazioni<0)
			printf("\nIl numero delle iterazioni deve essere maggiore di 0.");
	} 
	while (iterazioni==0 && iterazioni<0 && iterazioni>100000000);
	
	
	/* calcoliamo lo zero di f(x) */
	do {
		i++;
		m = (a+b)/2;
		fm = m-1/elevamento_potenza(e, m);
		if (stampa_dati== 1)
			printf("\na= %f, b= %f, f(a)= %f, f(b)= %f, m= %f, f(m)= %f  b-a= %f", a, b, fa, fb, m, fm, b-a);
		if(fm!=0){
			fa = a-1/elevamento_potenza(e, b);
			fb = b-1/elevamento_potenza(e, b);
		if(fa*fm<0)
			b=m;
		else a=m;
		fm = m-1/elevamento_potenza(e, b);
		}
	}
	while(fabs(fm) > ZERO && b-a > ZERO && i<iterazioni);
	
	printf("\n\nLo Zero di x-1/e^x dopo %d iterazioni è in %7.5f\n", iterazioni, m);
}

