Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the benefits of the following C code?

Tags:

c

Given log(a) and log(b), return log(a+b)

double log_sum(double log_a, double log_b){
    double v;
    if(log_a < log_b){
        v=log_b+log(1+exp(log_a-log_b));
    }
    else{
        v=log_a+log(1+exp(log_b-log_a));
    }
    return v;
}

I want to know what are the benefits of the above function?

like image 652
Charlie Epps Avatar asked Nov 26 '25 16:11

Charlie Epps


1 Answers

The primary (brute force) alternative looks like:

v = log(exp(log_a) + exp(log_b));

That has three transcendental function evaluations.

The computation shown uses just two transcendental functions - and should be quicker.

It may also be more stable numerically.

like image 193
Jonathan Leffler Avatar answered Nov 29 '25 11:11

Jonathan Leffler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!