deltaray
deltaray

Reputation: 432

How to assign a float value using GMP library in C?

I'm trying to learn how to use the GMP library in C by just writing a simple program to add some floating point numbers together, but at runtime it complains:

GNU MP: Cannot allocate memory (size=140735132293330)
Aborted (core dumped)

Here is the code:

#include <gmp.h>
#include <stdio.h>

int main(){
  mpf_set_default_prec(64);

  mpf_t sum;
  mpf_init(sum);
  mpf_set_ui(sum,0);
  unsigned int i = 0;

  while (i < 4) {
    mpf_add_ui(sum,sum,i);
    i++;
  }

  mpf_out_str(stdout,10,sum);
  printf ("\n");
  mpf_clear(sum);
}

I was able to do this with just the GMP mpz functions without issue, but when I try this with floats I'm stuck. The documentation doesn't really show any real examples for float functions so maybe I'm initializing or assigning the values incorrectly.

Upvotes: 1

Views: 1358

Answers (2)

Marc Glisse
Marc Glisse

Reputation: 7925

From the documentation,

it is a good idea to include stdio.h before gmp.h, since that will allow gmp.h to define prototypes for these functions

This way you get an error because you are calling the function with the wrong number of arguments. The reason you are not getting any warning for the lack of declaration is because mpf_out_str is a macro, defined in gmp.h which on your machine is installed in /usr/include and thus considered a system header, so the warning is disabled (use -Wsystem-headers to see it). This feels like a misfeature in gcc...

Upvotes: 3

Kerrek SB
Kerrek SB

Reputation: 477080

You must have not checked your compiler warnings properly, but the simple error is that you're calling mpf_out_str with the wrong number of arguments, which you can look up in the documentation:

size_t mpf_out_str (FILE *stream, int base, size_t n_digits, const mpf_t op)
//                                          ^^^^^^^^^^^^^^^^

Upvotes: 3

Related Questions