Goldberg's log1p vs. gsl_log1p

为君一笑 提交于 2019-12-11 10:09:20

问题


I am looking for a simple portable implementation of log1p. I have come across two implementations.

The first one appears as Theorem 4 here http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html,

An implementation of the above

double log1p(double p)
{
   volatile double y = p;
   return ( (1 + y) == 1 ) ? y : y * ( log( 1 + y) / ( ( 1 + y) - 1 ) );
}

The second one is in GSL http://fossies.org/dox/gsl-1.16/log1p_8c_source.html

double gsl_log1p (const double x)
{
  volatile double y, z;
  y = 1 + x;
  z = y - 1;
  return log(y) - (z-x)/y ; /* cancels errors with IEEE arithmetic */
}

Is there a reason to prefer one over the other?


回答1:


I have tested these two approaches using a log() implementation with a maximum error of < 0.53 ulps, comparing to a multi-precision arithmetic library. Using that log() implementation as a building block for the two log1p() variants, I found the maximum error of Goldberg's version to be < 1.51 ulps, while the maximum error in the GSL variant was < 0.67 ulps. This indicates the latter to be significantly more accurate.

In terms of special case handling, the Goldberg variant showed one mismatch, in that it returns a NaN for an input of +infinity, whereas the correct result is +infinity. There were three mismatches for special cases with the GSL implementation: Inputs of -1 and +infinity delivered a NaN, while the correct results should be -infinity and +infinity, respectively. Also, for an input of -0 this code returned +0, whereas the correct result is -0.

It is difficult to assess performance without knowledge of the distribution of the inputs. As others have pointed out in comments, Goldberg's version is potentially faster when many arguments are close to zero, as it skips the expensive call to log() for such arguments.




回答2:


There is no sure answer between the two. The GNU Scientific Library is quite robust, well used, and actively supported across all late versions of gcc. You are not as likely to run across too many surprises with its use. As for any other code you scrape up, there is absolutely no reason not to use it after you have validated its logic and are satisfied with its level/manner of error checking. The small downside to GSL is that it is another library you must carry around and depending on how widespread use of your code will be can provided more of a challenge for other users on other platforms. That is about the size of it.

The best piece of code is the one that most closely meets the requirements of your project.



来源:https://stackoverflow.com/questions/24134816/goldbergs-log1p-vs-gsl-log1p

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!