/* **************************************************************

   Uebungen zur Analysis I fuer Informatiker - WS 2003/04
   Blatt 6

   Freiwillige Zusatzaufgabe 30c)
   analysis30.cpp

   kthroot_approx (k, a, x0):
   Approximation an die k-te Wurzel von a, Startwert x0

   Leonhard Fellermayr, Mat. Nr. 22128130XXXX

   Auch im WWW: http://www.slacky.de/files/uni/analysis/analysis30.cpp

*************************************************************** */

#include <iostream>

const long double EPSILON_IEEE_64BIT = 1e-15;

void kthroot_approx (long double k, long double a, long double x0) {

	long double prev, curr;	   /* we need previous and current value */

	prev  = x0*2;	/* to pass break criteria when starting the loop */
	curr  = x0;

	int n = 0;					  /* counter var */

	printf ("\n%Lgth root of %Lg starting with %Lg:\n\n", k, a, x0);
	printf ("|   n |        xn         |   |xn - a^(1/k)|  |\n");
	printf ("-----------------------------------------------\n");

	while (not (fabsl (curr - prev) <= EPSILON_IEEE_64BIT * curr))
	{

		printf ("| %03d | %.15Lf | %.15Lf |\n", n, curr, fabsl (curr - powl (a, 1/k)));
		prev = curr; ++n;
		curr = 1/k * (((k-1) * prev) + (a / powl (prev, k-1)));

	}

} // kthroot_approx ()

int main ()
{

	kthroot_approx (2,   2, 5);
	kthroot_approx (3,  27, 5);
	kthroot_approx (5, 100, 5);

	return 0;

} // main ()

/*

	PROGRAMM-AUSGABE

2th root of 2 starting with 5:

|   n |        xn         |   |xn - a^(1/k)|  |
-----------------------------------------------
| 000 | 5.000000000000000 | 3.585786437626905 |
| 001 | 2.700000000000000 | 1.285786437626905 |
| 002 | 1.720370370370370 | 0.306156807997275 |
| 003 | 1.441455368177650 | 0.027241805804555 |
| 004 | 1.414470981367771 | 0.000257418994676 |
| 005 | 1.414213585796884 | 0.000000023423789 |
| 006 | 1.414213562373095 | 0.000000000000000 |

3th root of 27 starting with 5:

|   n |        xn         |   |xn - a^(1/k)|  |
-----------------------------------------------
| 000 | 5.000000000000000 | 2.000000000000000 |
| 001 | 3.693333333333333 | 0.693333333333333 |
| 002 | 3.122011871507369 | 0.122011871507369 |
| 003 | 3.004706248711931 | 0.004706248711931 |
| 004 | 3.000007367513256 | 0.000007367513256 |
| 005 | 3.000000000018093 | 0.000000000018093 |
| 006 | 3.000000000000000 | 0.000000000000000 |

5th root of 100 starting with 5:

|   n |        xn         |   |xn - a^(1/k)|  |
-----------------------------------------------
| 000 | 5.000000000000000 | 2.488113568490420 |
| 001 | 4.032000000000000 | 1.520113568490420 |
| 002 | 3.301274211058341 | 0.789387779548761 |
| 003 | 2.809404445343111 | 0.297518013833531 |
| 004 | 2.568573748712045 | 0.056687317202465 |
| 005 | 2.514333946640662 | 0.002447515131082 |
| 006 | 2.511891191817594 | 0.000004760308014 |
| 007 | 2.511886431527623 | 0.000000000018043 |
| 008 | 2.511886431509580 | 0.000000000000000 |


*/
