c语言使用mpfr库运算

1.计算目标

使用200-bit的精度计算1+1/1!+1/2!+...+1/100!

2.编写程序

#include 
#include 

int main (void)
{
        mpfr_t s, t, u;
        unsigned int i;

        mpfr_init2(t, 200);  //初始化变量为200-bit精度
        mpfr_set_d(t, 1.0, MPFR_RNDD);  //设置t=1.0
        mpfr_init2(s, 200);
        mpfr_set_d(s, 1.0, MPFR_RNDD);
        mpfr_init2(u, 200);

        for(i = 1; i <= 100; i++)
        {
                mpfr_mul_ui(t, t, i, MPFR_RNDU);  //设置t=t*i
                mpfr_set_d(u, 1.0, MPFR_RNDD);  //设置u=1.0
                mpfr_div(u, u, t, MPFR_RNDD);  //设置u=u/t
                mpfr_add(s, s, u, MPFR_RNDD);  //设置s=s+u
        }

        printf("Sum is ");

        mpfr_out_str(stdout, 10, 0, s, MPFR_RNDD);  //输出变量s的值

        putchar('\n');

        mpfr_clear(s);  //释放mpfr_t类型变量s
        mpfr_clear(t);
        mpfr_clear(u);

        mpfr_free_cache();  //释放mpfr缓存

        return 0;
}

3.编译程序

$ gcc -o example example.c -lmpfr -lgmp

4.运行程序

$ ./example

5.显示结果

Sum is 2.7182818284590452353602874713526624977572470936999595749669131

你可能感兴趣的:(c语言使用mpfr库运算)