简体   繁体   English

多幂实现

[英]Multi-Exponentiation Implementation

Is anyone aware of an implemented multi-exponentiation algorithm? 有人知道已实现的多幂运算算法吗? I'm looking for something that given vectors A, B would compute the product of A[i]^B[i] using some of the fast algorithms out there. 我正在寻找某种东西,给定向量A,B将使用其中的某些快速算法来计算A [i] ^ B [i]的乘积。

Thanks! 谢谢!

The following assumes that your data is floating point. 以下假设您的数据是浮点数。 If you have instead multi-precision integers, please specify your requirements. 如果您使用的是多精度整数,请指定您的要求。

The clean numerical way is of course to take the log first. 干净的数字方式当然是首先获取日志。 Indeed, partial products can easily under/overflow even if the result is finite. 实际上,即使结果有限,部分产品也很容易出现下溢/溢出现象。

The idiomatic corresponding C++ program is: 惯用的相应C ++程序是:

#include <cmath>
#include <functional>
#include <numeric>

double f(double x, double y)
{
    return y * std::log(x);
}

template <typename I, typename J>
double multi_exponentiation(I a0, I an, J b0)
{
    return std::exp(std::inner_product(a0, an, b0, 0., std::plus<double>(), f));
}

// Example program
int main()
{
    std::vector<double> a, b;
    ...
    double e = multi_exponentiation(a.begin(), a.end(), b.begin());
}

Using inner_product instead of writing the loop yourself has the advantage that once you know that performance is a problem , you can replace the inner_product algorithm with a parallel_inner_product algorithm provided by a third-party library (or write one yourself). 使用inner_product而不是自己编写循环的优点是, 一旦您知道性能是一个问题 ,就可以用第三方库提供的parallel_inner_product算法替换inner_product算法(或自己编写)。

How fast does this have to be? 这必须有多快? Depending on the size of your algorithm, the power function shouldn't be too much of a bottleneck. 根据算法的大小,幂函数不应成为太大的瓶颈。

You would write a simple function such as the following: 您将编写一个简单的函数,如下所示:

Vector VectorPower( Vector vec1, Vector vec2 )
{
      assert(vec1.length() == vec2.length());

      Vector vecAns( vec1.length() );

      for( unsigned int i = 0; i < vec1.length(); i++ )
      {
           vecAns[i] = pow( vec1[i], vec2[i] );
      }

      return vecAns;

}

Most of the time this will be efficient enough for your application. 在大多数情况下,这将对您的应用程序足够有效。 If you were implementing a square root or some other transcendental function, then you would have too look at optimization. 如果要实现平方根或某些其他先验函数,那么您也将不得不考虑优化。

Also, some processors are optimized for arbitrary integral powers, and GPUs certainly are (although that's not much help unless this is a Graphics related post, and isn't tagged as such). 另外,一些处理器针对任意整数幂进行了优化,并且GPU当然是可以解决的(尽管除非这是与Graphics相关的文章,并且没有这样的标签,否则这并没有太大帮助)。

Hope this answers your question :) 希望这能回答您的问题:)

Have you tried tommath (not sure it meets your performance requirement)? 您是否尝试过算命(不确定它是否满足您的性能要求)? Its multi-precision integer arith library! 它的多精度整数arith库!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM