C# Tutorial C# Advanced C# References

C# Math - Log() Method



The C# Log() method returns the natural logarithm or logarithm to the specified base of a given number. In special cases it returns the following:

  • If a is NaN or less than zero, the method returns NaN.
  • If Base is NaN or 1 or less than zero, the method returns NaN.
  • If a is positive infinity and 0 < Base < 1, the method returns negative infinity.
  • If a is positive infinity and Base > 1, the method returns positive infinity.
  • If a is zero and 0 < Base < 1, the method returns positive infinity.
  • If a is zero and Base > 1, the method returns negative infinity.
  • If a is 1 and Base is 0 or positive infinity, the method returns 0.
  • If a is not equal to 1 and Base is 0 or positive infinity, the method returns NaN.

Syntax

public static double Log (double a);
public static double Log (double a, double Base);

Parameters

a Specify the number whose logarithm is to be found.
Base Specify the base of the logarithm.

Return Value

Returns the natural logarithm or logarithm to the specified base of a given number.

Example:

In the example below, Log() method is used to calculate the natural logarithm of a given number.

using System;

class MyProgram {
  static void Main(string[] args) {
    Console.WriteLine("Math.Log(0) = "
                      + Math.Log(0));
    Console.WriteLine("Math.Log(10) = "
                      + Math.Log(10));
    Console.WriteLine("Math.Log(50) = "
                      + Math.Log(50));
    Console.WriteLine("Math.Log(Double.NaN) = "
                      + Math.Log(Double.NaN));
    Console.WriteLine("Math.Log(Double.NegativeInfinity) = "
                      + Math.Log(Double.NegativeInfinity));
    Console.WriteLine("Math.Log(Double.PositiveInfinity) = "
                      + Math.Log(Double.PositiveInfinity));
  }
}

The output of the above code will be:

Math.Log(0) = -Infinity
Math.Log(10) = 2.30258509299405
Math.Log(50) = 3.91202300542815
Math.Log(Double.NaN) = NaN
Math.Log(Double.NegativeInfinity) = NaN
Math.Log(Double.PositiveInfinity) = Infinity

Example:

In the example below, Log() method is used to calculate the specified base logarithm of a given number.

using System;

class MyProgram {
  static void Main(string[] args) {
    Console.WriteLine("Math.Log(10, 10) = "
                      + Math.Log(10, 10));
    Console.WriteLine("Math.Log(32, 2) = "
                      + Math.Log(32, 2));
    Console.WriteLine("Math.Log(9, 3) = "
                      + Math.Log(9, 3));
  }
}

The output of the above code will be:

Math.Log(10, 10) = 1
Math.Log(32, 2) = 5
Math.Log(9, 3) = 2

❮ C# Math Methods

5