【问题标题】:C GMP Non-Integer PowersC GMP 非整数幂
【发布时间】:2018-03-14 18:27:38
【问题描述】:

我正在使用 C GMP 库,我正在尝试计算一个浮点数,其中 mpf_t 类型的幂为 1.0 / n,其中 n 是一个 int。但是,这种类型的 pow 函数似乎只接受整数输入作为幂。这个库中是否有一个函数可以以双打的形式进行幂运算,如果没有,是否有我可以使用的快速算法?

【问题讨论】:

  • GMP 的浮点支持相当有限。您应该使用另一个库,例如 GNU MPFR(基于 GMP)。

标签: c gmp


【解决方案1】:

这个库中是否有一个函数可以以以下形式执行权力 双打,

没有。

如果没有,有没有我可以使用的快速算法?

是的。

x1.0/n 的幂等于n 的平方根x。并且有一个有效的算法来计算,请参阅: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

【讨论】:

    猜你喜欢
    • 2012-02-10
    • 1970-01-01
    • 1970-01-01
    • 2015-08-30
    • 2013-07-17
    • 2016-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多