我正在使用 C GMP 库,我正在尝试计算 mpf_t 类型的 float 的 1.0/n 次方,其中 n 是一个整数。但是,这种类型的 pow 函数似乎只接受整数输入作为幂。该库中是否有可以以 double 形式执行幂运算的函数?如果没有,是否有我可以使用的快速算法?
最佳答案
Is there a function in this library that can do powers in the form of doubles,
没有。
and if not, is there a fast algorithm I can make use of instead?
是的。
1.0/n
的 x
与 x
的平方 n
根相同。并且有一种有效的算法可以计算,请参阅:nth root algorithm - Wikipedia
这是工作的 C 代码,您可以轻松地适应 GMP。
功能:
void mpf_pow_ui (mpf_t rop, const mpf_t op1, unsigned long int op2);
- 将rop
设置为op1
的op2
次方,可以用来代替dexp
。
#include <stdlib.h>
#include <stdio.h>
double dexp(double a, double toN){
double ret = 1;
for(int i = 0; i< toN; ++i)
ret *= a;
return ret;
}
double nth_root(double num, int N, double precision){
double x;
double dx;
double eps = precision;
double A = num;
double n = N;
x = A * 0.5;
dx = (A/dexp(x,n-1)-x)/n;
while(dx >= eps || dx <= -eps){
x = x + dx;
dx = (A/dexp(x,n-1)-x)/n;
}
return x;
}
int main()
{
int N = 4;
int A = 81.0;
double nthRootValue = nth_root(A, N, 10e-8);
printf("Nth root is %lf", nthRootValue);
return 0;
}
测试:
Nth root is 3.000000
关于C GMP 非整数幂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49285214/