Home Communities
IT Knowledge
Inspiration
Languages
EN

# C# / .NET - Math.Log() method example

0 points
Created by:
327

The `Math.Log()` method returns the natural logarithm (base e) of a number.

``````using System;

public class Program
{
public static void Main(string[] args)
{
// Natural logarithm (logarithm with base e):
//                           x            y
Console.WriteLine( Math.Log( 1    ) ); // 0
Console.WriteLine( Math.Log( 7    ) ); // 1.9459101490553132
Console.WriteLine( Math.Log( 10   ) ); // 2.3025850929940460
Console.WriteLine( Math.Log( 100  ) ); // 4.6051701859880920
Console.WriteLine( Math.Log( 1000 ) ); // 6.9077552789821370

Console.WriteLine( Math.Log( -1                      ) ); // NaN
Console.WriteLine( Math.Log(  0                      ) ); // -∞ / -Infinity
Console.WriteLine( Math.Log( Double.PositiveInfinity ) ); //  ∞ / +Infinity

Console.WriteLine( Math.E ); // 2.718281828459045

// Logarithm with custom base is placed in the below example.
}
}``````

The `Math.Log()` method is presented on the following chart:

## 1. Documentation

 Syntax ``````namespace System { public static class Math { // ... public static double Log(double a, double newBase) { ... } public static double Log(double d) { ... } // ... } }`````` Parameters `a`, `d` - double value in the range `0` to `+Infinitive` (primitive value). `newBase` - logarithm base. Result `number` value calculated as ln(x) mathematical function (primitive value). If `x` is negative it returns `NaN`. If `x` is equal to `0` it returns `-Infinity`. If `x` is equal to `+Infinity` it returns `-Infinity`. Description `Log` is a static method that takes one parameter and returns an approximation of the ln(x) function (natural logarithm function - logarithm with base `e`).

## 2. Logarithm with custom base example

This example shows a logarithmic function calculation with its own base.

``````using System;

public class Program
{
static double calculateLogarithm(double logBase, double x)
{
double a = Math.Log(x);
double b = Math.Log(logBase);

return a / b;
}

public static void Main(string[] args)
{
// Logarithm with custom base:
//                                    base     x               y
Console.WriteLine( calculateLogarithm( 2,      2      ) ); //  1
Console.WriteLine( calculateLogarithm( 2,      4      ) ); //  2
Console.WriteLine( calculateLogarithm( Math.E, Math.E ) ); //  1
Console.WriteLine( calculateLogarithm( 3,      9      ) ); //  2
Console.WriteLine( calculateLogarithm( 3,      81     ) ); //  4
Console.WriteLine( calculateLogarithm( 10,     10     ) ); //  1
}
}``````

## References

1. Natural logarithm - Wikipedia

Join to our subscribers to be up to date with content, news and offers.

## Cross technology - Math.log()

##### 🚀
Get your tech brand or product in front of software developers.

Join