如何使用printf与mpfr和mpreal [英] How to use printf with mpfr and mpreal
问题描述
使用 printf
及其表兄弟 sprintf
和 fprintf
显示 mpreal
-type变量的值?我尝试了天真的转换为双重:
What is the correct syntax for using printf
and its cousins sprintf
and fprintf
to display the value of mpreal
-type variables? I have tried the naive casting to double:
printf ("... %g ...", (double) var);
仅接收来自g ++的此错误消息:
only to receive this error message from g++:
error: invalid cast from type ‘mpfr::mpreal’ to type ‘double’
我在程序的其他地方使用 double
- 类型变量没有问题。
I had no problem using double
-type variables elsewhere on the program.
我听说过<图书馆的一部分 mpreal
类型
推荐答案
mpreal
是任意精度浮点数值类型。
The mpreal
is arbitrary precision floating-point numerical type.
因此, mpreal
数字可能有比<$ c $更多的有效数字(甚至数百或千分之一) c> double 。这意味着无意义 mpreal
到 double
As such, mpreal
numbers might have much more significant digits (even hundreds or thousandths) than double
. Which means it is pointless to round mpreal
to double
before display - you will lose all the original accuracy in this case.
很容易在C ++中显示 mpreal
:
It is easy to display mpreal
in C++:
/* 100-digits accurate pi */
mpreal pi = mpfr::const_pi(mpfr::digits2bits(100));
/* Show 60-digits of pi */
cout.precision(60);
cout << pi;
$ b (通过首先转换为字符串):
However you can use it with printf
as well (by converting to string first):
/* Display all digits (default formatting) */
printf("pi = %s\n", pi.toString().c_str());
/* Custom format, 60 digits */
printf("pi = %s\n", pi.toString("%.60RNf").c_str());
/* Using native printf from MPFR*/
mpfr_printf("pi = %.60RNf\n", pi.mpfr_srcptr());
多精度数的格式规范与标准规范相同,但舍入规范除外。您可以安全地使用舍入到最接近的 RN
,如上面的例子。
Format specification for multiple-precision numbers are the same as for standard with the exception to rounding specification. You can safely use rounding to nearest,RN
as in examples above.
更多细节的mp格式化在 MPFR文档中。
More details on mp-formatting are given in MPFR documentation.
(我是 mpreal
的作者 MPFR C ++ )
这篇关于如何使用printf与mpfr和mpreal的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!