Skip to content

Instantly share code, notes, and snippets.

@AndrewBarfield
Created April 30, 2012 10:27
Show Gist options
  • Save AndrewBarfield/2557117 to your computer and use it in GitHub Desktop.
Save AndrewBarfield/2557117 to your computer and use it in GitHub Desktop.
C#: Calculate the Exponential Function exp(x) using Taylor Expansion
using System;
namespace EulerNumberTaylorExpansion
{
class Program
{
/// <summary>
/// See: http://en.wikipedia.org/wiki/Exponential_function
/// See: http://en.wikipedia.org/wiki/Taylor_expansion
/// </summary>
/// <param name="args"></param>
static void Main( string[] args )
{
// Print Banner
Console.WriteLine(
"\nCSC 340 Scientific Computing\n" +
"Calculate exp(3.7) using Taylor's Expansion\nAndrew M. Barfield\n" +
DateTime.Now.ToLongDateString() + "\n" +
DateTime.Now.ToLongTimeString() +
"\n\n" );
Console.WriteLine( "exp(3.7) = " + CalculateExp( 3.7 ).ToString("##.###") );
Console.Read();
}
/// <summary>
/// Calculate exp(x) using Taylor Expansion
/// </summary>
/// <param name="x">Exponent for Euler's Number</param>
/// <returns>Returns exp(x)</returns>
static double CalculateExp( double x )
{
// Holds and returns final answer
double answer = 0;
// Holds previous answer and is used to stop Taylor Expansion
double oldanswer = 0;
// Summation index variable
double k = 0;
// Refine the solution by adding more terms to the Taylor Expansion.
// Stop when the answer doesn't change.
while ( true )
{
answer += Math.Pow( x, k ) / Factorial( k );
if ( answer == oldanswer )
{
break;
}
else
{
oldanswer = answer;
k++;
}
}
// Write directly to the console here to avoid global variable
Console.WriteLine( "Answer calculated in " + k.ToString() + " iterations." );
// Return solution to caller
return answer;
}
/// <summary>
/// Calculate the factorial for x
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
static double Factorial( double x )
{
double answer = 1;
double counter = 1;
while ( counter <= x )
{
answer = answer * counter;
counter++;
}
return answer;
}
}
}
CSC 340 Scientific Computing
Calculate exp(3.7) using Taylor's Expansion
Andrew M. Barfield
Thursday, January 15, 2009
1:56:36 PM
Answer calculated in 29 iterations.
exp(3.7) = 40.447
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment