Search code examples
cpimpfr

arbitrary floating precision number to string


I am new to c programming language. What I am trying to do is to get store pi in arbitary precision and turn that to string.

int calculatePIConst (int preciznost)
{
    //init var
    mpfr_t x;
    mpfr_init2 (x, preciznost);
    //populate pi
    mpfr_const_pi (x, MPFR_RNDN);
    //turn to string
    char abc[preciznost];
    int i;
    //error RUN FINISHED; Segmentation fault; core dumped; real time: 90ms; user: 0ms; system: 0ms
    //  mpfr_get_str (abc, i, 50, 50, x, MPFR_RNDN);
    //write pi
    mpfr_printf ("PI = %1.1024RNf\n", x);
    mpfr_clear (x);
    return *abc;
}

Here is mpfr lib documentation documentation http://www.mpfr.org/mpfr-current/mpfr.html#Miscellaneous-Functions


Solution

  • From the documentation you linked to:

    If str is not a null pointer, it should point to a block of storage large enough for the significand, i.e., at least max(n + 2, 7). The extra two bytes are for a possible minus sign, and for the terminating null character, and the value 7 accounts for -@Inf@ plus the terminating null character.

    Also, I assume you want your result in base 10, not base 50.

    Try this:

    char abc[preciznost + 2]; /* assuming preciznost >= 5 */
      :
    mpfr_get_str (abc, i, 10, 50, x, MPFR_RNDN);