C中的logsumexp实现? [英] logsumexp implementation in C?

查看:71
本文介绍了C中的logsumexp实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有谁知道提供 logsumexp 函数的开源数字 C 库?

Does anybody know of an open source numerical C library that provides the logsumexp-function?

logsumexp(a) 函数计算数组 a 的分量的指数 log(e^{a_1}+...e^{a_n}) 的总和,避免数值溢出.

The logsumexp(a) function computes the sum of exponentials log(e^{a_1}+...e^{a_n}) of the components of the array a, avoiding numerical overflow.

推荐答案

这是一个非常简单的从头开始的实现(经过测试,至少是最低限度的):

Here's a very simple implementation from scratch (tested, at least minimally):

double logsumexp(double nums[], size_t ct) {
  double max_exp = nums[0], sum = 0.0;
  size_t i;

  for (i = 1 ; i < ct ; i++)
    if (nums[i] > max_exp)
      max_exp = nums[i];

  for (i = 0; i < ct ; i++)
    sum += exp(nums[i] - max_exp);

  return log(sum) + max_exp;
}

这可以有效地将所有参数除以最大的参数,然后在最后重新添加其日志以避免溢出,因此添加大量类似缩放的值时表现良好,错误不断增加如果某些参数比其他参数大许多数量级.

This does the trick of effectively dividing all of the arguments by the largest, then adding its log back in at the end to avoid overflow, so it's well-behaved for adding a large number of similarly-scaled values, with errors creeping in if some arguments are many orders of magnitude larger than others.

如果您希望它在给定 0 个参数时运行而不会崩溃,则必须为此添加一个案例:)

If you want it to run without crashing when given 0 arguments, you'll have to add a case for that :)

这篇关于C中的logsumexp实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆