Search code examples
c++mathlogarithm

C++ math expression from math formula


I try to convert this math formula in C++ expression

Expression

But I'm doing something wrong

(log(1.0+a*(getpixel(j,k)))/log10( y ))/(log(2.0)/log10( y ))

Solution

  • First, the log function already computes the logarithm to the base e. You don't need to perform any change-of-base.

    Second, split your expression into parts to make it easier to write, and to understand:

    const double F = getpixel(j, k);
    const double numerator = log(1.0 + a * F);
    const double denominator = log(2.0);
    const double result = numerator / denominator;
    

    You could choose to split it more (e.g. store the a*F, and 1 + a*F separately too).

    Once you've got that, if you really want it in a single line, it's easy enough to combine (but there's no need; the compiler will typically merge constant expressions together for you):

    const double result = log(1.0 + a * getpixel(j, k) / log(2.0);