C GMP 非整数幂

标签 c gmp

我正在使用 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/nxx 的平方 n 根相同。并且有一种有效的算法可以计算,请参阅:nth root algorithm - Wikipedia

这是工作的 C 代码,您可以轻松地适应 GMP。

功能:

void mpf_pow_ui (mpf_t rop, const mpf_t op1, unsigned long int op2);

- 将rop 设置为op1op2 次方,可以用来代替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/

相关文章:

c++ - 最快的 C++ 有理数库

c - 尝试从结构指针 : compiles but does not run 访问 int

c++ - SQLite 中的语法错误(C 绑定(bind))

c - 对分形实现缩放

c - 在 C 程序中使用 GMP 整数函数的正确方法是什么?

C++ GMP 库 ostream operator<< 编译但不链接?

c - C 中的 GMP 库 - 如何使添加更精确?

c++ - 在 Windows 上使用 gmplib 编译 cpp 代码时的链接问题

c - 如何使用带有 CTest 的检查库在 C 中进行单元测试

c - 如何使用 sizeof 运算符计算出使用多少字节来存储 C 中的变量?