C++ MPFR库:如何添加两个mprf_t变量并打印结果?
我正在搜索一些说明mpfr库的示例,但找不到任何有用的 我想创建两个变量,可以容纳多达100位的浮点数 必须使用字符串初始化这些变量 然后我想添加它们并将结果打印到屏幕上 我发现这个代码:C++ MPFR库:如何添加两个mprf_t变量并打印结果?,c++,floating-point-precision,mpfr,C++,Floating Point Precision,Mpfr,我正在搜索一些说明mpfr库的示例,但找不到任何有用的 我想创建两个变量,可以容纳多达100位的浮点数 必须使用字符串初始化这些变量 然后我想添加它们并将结果打印到屏幕上 我发现这个代码: #include <stdio.h> #include <gmp.h> #include <mpfr.h> int main(void) { unsigned int i; mpfr_t s, t, u; mpfr_init2(t, 200);
#include <stdio.h>
#include <gmp.h>
#include <mpfr.h>
int main(void)
{
unsigned int i;
mpfr_t s, t, u;
mpfr_init2(t, 200);
mpfr_set_d(t, 1.0, GMP_RNDD);
mpfr_init2(s, 200);
mpfr_set_d(s, 1.0, GMP_RNDD);
mpfr_init2(u, 200);
for (i = 1; i <= 100; i++)
{
mpfr_mul_ui(t, t, i, GMP_RNDU);
mpfr_set_d(u, 1.0, GMP_RNDD);
mpfr_div(u, u, t, GMP_RNDD);
mpfr_add(s, s, u, GMP_RNDD);
}
printf("Sum is ");
mpfr_out_str(stdout, 10, 0, s, GMP_RNDD);
putchar('\n');
mpfr_clear(s);
mpfr_clear(t);
mpfr_clear(u);
return 0;
}
然后我尝试了以下代码:
#include <stdio.h>
#include <gmp.h>
#include <mpfr.h>
int main(void)
{
unsigned int i;
mpfr_t s, t, u;
//add numbers 1.456774343454354355435354325213 and
//14.456774343454354355435354325213
mpfr_init2(t, 200);
mpfr_set_d(t, 1.456774343454354355435354325213, GMP_RNDD);
mpfr_init2(s, 200);
mpfr_set_d(s, 14.456774343454354355435354325213, GMP_RNDD);
mpfr_init2(u, 200);
mpfr_add(u, s, t, GMP_RNDD);
printf("Sum is ");
mpfr_out_str(stdout, 10, 0, u, GMP_RNDD);
putchar('\n');
mpfr_clear(s);
mpfr_clear(t);
mpfr_clear(u);
return 0;
}
结果
总额为1.5913548686908708384990518425183637070655822753906250000E1
这是错误的,至少应该是2你的结果在我看来很好。你注意到字符串末尾的e1了吗?还要注意的是,你是从double开始初始化s和t的,所以在转换必须加倍的长十进制文本时,你已经失去了相当多的精度。与解释为小数时的文字总数相比,您应该只希望前16位数字是准确的。现在您还可以使用mpfr_printf输出mpfr数字。例如,mpfr\u printf Sum是%.60Rf\n,u;将输出15.91354868690870838499051842518363707065582275390625000000,这在这里更清楚。是否可以使用字符串初始化mpfr类,以便在初始化过程中不使用任何精度?@jsguy是的,您可以使用mpfr_set_str从字符串设置值。请参阅有关此主题的详细信息。