The following program computes a lower bound on 1+1/1!+1/2!+...+1/100!
using 200-bit precision: mpfr_t s, t, u; declares three
floating-point variables s, t, u;
mpfr_init2 (t, 200); initializes the variable t with
200-bit precision; then mpfr_set_d (t, 1.0, GMP_RNDD); sets the
value of t to the double-precision number 1.0 rounded towards
minus infinity (here no rounding is done since 1 can be represented exactly
on 200 bits); the statement mpfr_mul_ui (t, t, i, GMP_RNDU);
multiplies t in place by the unsigned integer i,
where the result is rounded towards plus infinity;
mpfr_div (u, u, t, GMP_RNDD); divides u by
t, rounds the result towards minus infinity and stores it
into u; then the statement
mpfr_out_str (stdout, 10, 0, s, GMP_RNDD); prints the value of
s in base 10, rounded towards minus infinity, where the third
argument 0 means that the number of printed digits is automatically chosen
from the precision of s; finally the mpfr_clear
calls free the space used by the MPFR
variables.
#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;
}
The result of this program is:
$ ./sample Sum is 2.718281828459045235360287471352662497757247093699959574966913