There is actually nothing wrong with your code except that decimals won't work for
Math.Pow
and
Math.Sqrt
. After just two iterations all the digits are already correct. At least they were on my PC. :)
Here the example I worked with (C# WindowsForms):
namespace PI
{
public partial class Form1 : Form
{
static double alpha = 6d - 4d * Math.Sqrt(2d);
static double piY = Math.Sqrt(2d) - 1d;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int iterations = int.Parse(textBox2.Text);
GetPi(iterations);
}
private double GetPi(int n)
{
double result;
double TempAlpha, TempYPi;
TempAlpha = alpha;
TempYPi = piY;
result = 1d / TempAlpha;
textBox1.Clear();
for(int i = 1; i<=n; i++)
{
TempYPi = (1d - Math.Pow((1d - Math.Pow(TempYPi, 4d)), 1d / 4d)) / (1d + Math.Pow((1d - Math.Pow(TempYPi, 4d)), 1d / 4d));
TempAlpha = Math.Pow(1d + TempYPi, 4d) * TempAlpha - Math.Pow(2d, 2d * ((double)i - 1d) + 3d) * TempYPi * (1d + TempYPi + Math.Pow(TempYPi, 2d));
result = 1d / TempAlpha;
textBox1.Text += String.Format("{0} : {1}\r\n", i, result);
}
return result;
}
}
}
The output for 2 iterations is:
1 : 3,14159264621355
2 : 3,14159265358979
PI: 3,1415926535897932384626433832795028841971693993751058209...
As you can easily see after just 2 iteration the precision for double is already exhausted an all the digits calculated are already correct.
Regards,
Manfred