0

I've been playing around with some math recently and I would like to know if anyone has written/seen a C++ implementation of log that one can specify the base (root..?) for? As in:

Mathematical function definition http://i1091.photobucket.com/albums/i383/dannydeth1/forumla.png

Obviously I would prefer giving the base as an argument: double d = log(b,x);

Thank you for your time and any answers are much appreciated. :}

EDIT: Also, I take it would use Taylor Series?

hammar
  • 138,522
  • 17
  • 304
  • 385
Erkling
  • 509
  • 4
  • 16

2 Answers2

18

log_b_(x) = log(x) / log(b). Just do this:

double log(double base, double x)
{
    return std::log(x) / std::log(base);
}
Mankarse
  • 39,818
  • 11
  • 97
  • 141
voltrevo
  • 9,870
  • 3
  • 28
  • 33
9

It's straightforward to implement yourself:

double
logb( double n, double b )
{
    return log(n) / log(b);
}

Is it generally useful? Or are practically all of the uses subsumed by log, log10 and log2?

James Kanze
  • 150,581
  • 18
  • 184
  • 329
  • Does `log10` exist for convenience only, or because it's typically more accurate than `log(x)/log(10)`? If the latter, then it's not necessarily straightforward to implement `logb` "properly": there might be a more accurate implementation than this, even though `b` isn't fixed. – Steve Jessop Nov 30 '11 at 12:44
  • `log10` exists because the standard requires it to exist:-). I think it is more convenience; IIRC, it was present in the earliest Unix, and a lot of the math functions then had horrible precision. With regards to the precision, I'm not sure that distinct implementations would necessarily give better precision (especially on machines with extended precision FP registers); they could certainly be faster, however. Which could also be a motivation. (WRT precision, the standard also requires a `log1p` function, which **is** motivated strictly by precision.) – James Kanze Nov 30 '11 at 14:30