log10 function in C

The log10 function in C computes the base-10 (common) logarithm of x. A domain error occurs if the argument is negative. A pole error may occur if the argument is zero. The x is the argument that is passed into the log10().

It is declared in math.h and takes one argument in the form of double and returns the value of type double.

 

Syntax of log10 function in C:

//Syntax of log10

double log10(double x);

Parameters:

x => floating types (double)

Return value:

The log function return log10(x).

 

You can use the log10f() function to work specifically with float and log10l() to work with long double type. See the below syntax.

//syntax of log functions

float log10f(float x);

long double log10l(long double x);

 

 

C program to understand the working of log10 function:

Below mentioned C example code shows the usage of log10().

Example 1:

#include <stdio.h>
#include <math.h>

int main()
{
    double x = 4.2, result;

    result = log10(x);
    printf("log(%lf) = %lf", x, result);

    return 0;
}

Output:

log(4.200000) = 0.623249

 

Example 2:

#include <stdio.h>
#include <math.h>

int main()
{
    double x = 10, result;

    result = log10(x);
    printf("log(%lf) = %lf", x, result);

    return 0;
}

Output:

log(10.000000) = 1.000000

 

 

Error handling

  • Errors are reported as specified in math_errhandling.
  • Domain error occurs if arg is less than zero.
  • Pole error may occur if arg is zero.

If the implementation supports IEEE floating-point arithmetic (IEC 60559),

  • If the argument is ±0, -∞ is returned and FE_DIVBYZERO is raised..
  • If the argument is 1, +0 is returned.
  • If the argument is negative, NaN is returned and FE_INVALID is raised.
  • If the argument is +∞, +∞ is returned.
  • If the argument is NaN, NaN is returned.
#include <stdio.h>
#include <math.h>
#include <float.h>
#include <errno.h>
#include <fenv.h>

#pragma STDC FENV_ACCESS ON

int main()
{
    // special values
    printf("log10(1) = %f\n", log10(1));
    printf("log10(+Inf) = %f\n", log10(INFINITY));

    //error handling
    errno = 0;
    feclearexcept(FE_ALL_EXCEPT);
    printf("log10(0) = %f\n", log10(0));
    if(errno == ERANGE)
    {
        perror("errno == ERANGE");
    }
    if(fetestexcept(FE_DIVBYZERO))
    {
        puts("FE_DIVBYZERO raised");
    }

    return 0;
}

Output:

log10(1) = 0.000000
log10(+Inf) = inf
log10(0) = -inf
errno == ERANGE: Numerical result out of range
FE_DIVBYZERO raised

 

Recommended Post: