Tuesday, November 30, 2010

Project Ideas

I've stumbled on an interesting coder's project ideas list



Then tackled the first one in my own way. The goal is to

Find PI to the Nth Digit – Enter a number and have the program generate PI up to that many decimal places. Keep a limit to how far the program will go.


Rather than do exactly that, I wanted to start small, and work through some of the existing formulas I could find and put them into C#. That would be a step in the right direction towards the goal. I think the actual project idea is currently out of my range, with little to gain from going farther than I did. I learned much more about floating point math, decimal vs. double, and binary vs. decimal vs. hexadecimal math.


Code Follows:







/// <summary>
  /// http://en.wikipedia.org/wiki/Pi
  /// </summary>
  /// <seealso cref="http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems"/>
public static class PiCalculator
  {
    /// <summary>
    /// http://en.wikipedia.org/wiki/Numerical_approximations_of_%CF%80
    /// </summary>
    /// <returns></returns>
    public static double Euler( )
    {
      return 20*Math.Atan((double)1/7)+8*Math.Atan((double)3/79);
    }
    public static double MachinLike( )
    {
      return 4*(4*Math.Atan((double)1/5)-Math.Atan((double)1/239));
    }
    public static double Archimedes1( )
    {
      double archimedes1=0;

      //most accurate number this formula can give on a computer
      const double magicNumber = 16;

      double previousT=1.0/Math.Sqrt(3.0);
      for (double i = 0; i<magicNumber+1; i++)
      {
        archimedes1=6.0*Math.Pow(2.0, i)*previousT;
        previousT=(Math.Sqrt(Math.Pow(previousT, 2.0)+1.0)-1.0)/previousT;
      }
      return archimedes1; //gives the expected 8 digits of precision 
      // 3.1415926 wrong digits - 7174155

    }
    public static double Archimedes2( )
    {
      //most accurate number this formula can give on a computer
      const double magicNumber = 23;
      double archimedes2 = 0;
      double previousT=1.0/Math.Sqrt(3.0);
      for (double i = 0; i<magicNumber+1; i++)
      {
        archimedes2=6.0*Math.Pow(2.0, i)*previousT;
        previousT=previousT/(Math.Sqrt(Math.Pow(previousT, 2)+1)+1.0);
      }
      return archimedes2; //returns 13 digits of precision instead of the expected 15
      // returns 3.1415926535898 instead of 3.14159265358979

    }
    /// <summary>
    /// http://pi.lacim.uqam.ca/eng/approximations_en.html
    /// </summary>
    /// <returns></returns>
    public static double Plouffe()
    {
      return Math.Log10((double) 28102/1277)*(double) 125/123;
    }

    public static double Plouffe2()
    {
      return Math.Pow(276694819753963.0/226588, 1.0/158.0)+2.0;
    }

  }

No comments:

Post a Comment