find the base e logarithm of a number in csharp

To find the natural logarithm (logarithm with base e) of a number in C#, you can use the Math.Log method with base e (i.e., with no second argument):

main.cs
double x = 10;
double naturalLog = Math.Log(x); // this gives the natural logarithm of x

Console.WriteLine(naturalLog); // prints 2.30258509299405
148 chars
5 lines

If you want to specify a different base, you can use the overload of Math.Log that takes two arguments. The first argument is the number to take the logarithm of, and the second argument is the base:

main.cs
double x = 10;
double base2Log = Math.Log(x, 2); // this gives the base-2 logarithm of x

Console.WriteLine(base2Log); // prints 3.32192809488736
146 chars
5 lines

Note that the Math.Log method returns a double value, which means that it has limited precision. If you need higher precision, you can use the Math.Log(double, double) overload that takes the base as the second argument. Alternatively, you can use the System.Numerics.Complex library to perform complex number logarithms.

gistlibby LogSnag