B. Wilson
B. Wilson

Reputation: 101

How to write log function in c++

I'm trying to write the log function in my program. I found this on cplusplus.com:

/* log example */
#include <stdio.h>      /* printf */
#include <math.h>       /* log */

int main ()
{
  double param, result;
  param = 5.5;
  result = log (param);
  printf ("log(%f) = %f\n", param, result );
  return 0;
}

This calculates the log of 5.5 to be: 1.704708. When I put the log of 5.5 into my calculate I get: .740362. Why is this code giving incorrect values?

Upvotes: 2

Views: 3827

Answers (2)

Madhav Datt
Madhav Datt

Reputation: 1083

log (5.5) is log with base 10 and is equal to 0.740362.

You are looking for the Natural log function, ie. with base e.

Use the cmath header, instead of the math.h header for natural log.

std::log (5.5); // Gives natural log with base e
std::log10 (5.5); // Gives common log with base 10

Read more here

Upvotes: 5

CJCombrink
CJCombrink

Reputation: 3950

To follow up on what Madhav Datt said, if you are looking for the natural log then rather use the cmath header:

  • std::log(): Computes the the natural (base e) logarithm of arg.
  • std::log10(): Computes the common (base-10) logarithm of arg.

Upvotes: 4

Related Questions