Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Exp vs. Log: Which is faster?

I have a C++ application in which I need to compare two values and decide which is greater. The only complication is that one number is represented in log-space, the other is not. For example:

double log_num_1 = log(1.23);
double num_2 = 1.24;

If I want to compare num_1 and num_2, I have to use either log() or exp(), and I'm wondering if one is easier to compute than the other (i.e. runs in less time, in general). You can assume I'm using the standard cmath library.

In other words, the following are semantically equivalent, so which is faster:

if(exp(log_num_1) > num_2)) cout << "num_1 is greater";

or

if(log_num_1 > log(num_2)) cout << "num_1 is greater";
like image 557
Kyle Simek Avatar asked May 03 '09 16:05

Kyle Simek


2 Answers

Do you really need to know? Is this going to occupy a large fraction of you running time? How do you know?

Worse, it may be platform dependent. Then what?

So sure, test it if you care, but spending much time agonizing over micro-optimization is usually a bad idea.

like image 125
dmckee --- ex-moderator kitten Avatar answered Sep 18 '22 22:09

dmckee --- ex-moderator kitten


AFAIK the algorithms, the complexity is the same, the difference should be only a (hopefully negligible) constant. Due to this, I'd use the exp(a) > b, simply because it doesn't break on invalid input.

like image 37
peterchen Avatar answered Sep 19 '22 22:09

peterchen