Showing posts with label Math. Show all posts
Showing posts with label Math. Show all posts

Tuesday, November 30, 2010

Project Ideas Numbers - Fibonacci Sequence

Tackling the Fibonacci project was far easier but still yielded new knowledge.

Recursion is horrible on performance compared to iterative or tail-recursion (assuming the compiler supports tail optimization).


public static class FibonacciSequence
  {
    public static long CalculateRecurse(int term)
    {
      if (term<1)
        throw new ArgumentOutOfRangeException("term""must be >0");
      const byte f0 = 0;
      const byte f1 = 1;
      if (term<2)
        return term;
      return CalculateRecurse(term-1)+CalculateRecurse(term-2);
    }
    public static long CalculateWhile(int term)
    {
      int i = 1, k = 0;
      while (i<=term)
      {
        k+=i;
        ++i;
      }
      return k;
    }
 
    public static long CalculateTail(int term)
    {
      if (term<1)
        throw new ArgumentOutOfRangeException("term""must be >0");
      return CalculateTail(term, 1, 1);
    }
 
    private static long CalculateTail(int term, int iter, int acc)
    {
      if (iter==term)
        return acc;
      return CalculateTail(term, ++iter, acc+iter);
    }
  }

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: