Friday, June 22, 2012

Exponential, Logarithmic and Power Functions in ANSI C

To use exponential, logarithmic and power functions in ANSI C, you will need to include the mathematics header:
#include<math.h>
1.Exponential Functions
ANSI C mathematical library provides functions for computing e (Euler's constant) and 2 raised at a given power.

Example
 double n = 3.2;
 /*Computes v1 = e^n*/
 double v1 = exp(n);
 /*Computes v2 = e^n*/
 double v2 = exp2(n);
 /*Computes v3 = (e^n)-1. It provides better precision than
  *exp(m)-1 when the result is close to 0*/
 double v3 = expm1(n);
2.Logarithmic Functions
ANSI C mathematical library provides functions for computing the natural (e), common (10) and base 2 logarithm for a given number.

Example
 double n = 3.2;
 /*Computes the natural logarithm of n*/
 double v1 = log(n);
 /*Computes the common logarithm of n*/
 double v2 = log10(n);
 /*Computes the base 2 logarithm of n*/
 double v3 = log2(n);
 /*Computes the natural algorithm of (1+n).It provides
  *more accurate results than using log(n+1) when n
  *is close to 0*/
 double v3 = log1p(n);
3.Power functions
ANSI C mathematical library provides functions for computing the power, square root, cubic root of a given number and the square root of the sum of the squares of 2 given numbers.

Example
 double n1 = 3.2, n2 = 3.6;
 /*Computes v1 = n1^3*/
 double v1 = pow(n1,3.0);
 /*Computes the square root of n1*/
 double v2 = sqrt(n1);
 /*Computes the cubic root of n1*/
 double v3 = cbrt(n1);
 /*Computes v4 = sqrt(pow(n1,2)+pow(n2,2))*/
 double v4 = hypot(n1,n2);
Note:
All compilers compliant with C99 should have functions that allow you to use the float and long double data type in the same way we used double.

All functions that operate with float will have have the same name as their double counterparts plus the -f suffix
Example: float logf(float arg)

All functions that operate with long double will have have the same name as their double counterparts plus the -l suffix
Example: long double cbrtl(long double n1, long double n2)

Mathematical notions:

No comments:

Post a Comment

Got a question regarding something in the article? Leave me a comment and I will get back at you as soon as I can!

Related Posts Plugin for WordPress, Blogger...
Recommended Post Slide Out For Blogger