Floating Point Confusion
Rob Crowther
weilawei at gmail.com
Wed Sep 19 18:44:44 CEST 2007
I'm trying to write a wrapper for GNU MP for the upcoming version of Python,
but I'm stuck at figuring out how to get the component parts of an mpf_t.
The current code I have works for most things, but values such as 0.01 don't
seem to exist at all!
Small example, which I've been using to try and figure things out:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <gmp.h>
#define MPF_DEFAULT_PREC 128
#define MPF_DEFAULT_BASE 10
#define MPF_DEFAULT_SIGFIGS (size_t) 0
int main(int argc, char *argv[]) {
mpf_t x;
size_t sigfigs = MPF_DEFAULT_SIGFIGS;
unsigned long int base = MPF_DEFAULT_BASE;
unsigned long int whole = 0;
unsigned long int decimal = 0;
mp_exp_t exponent;
char *value = NULL;
char *s_whole = NULL;
mpf_set_default_prec(MPF_DEFAULT_PREC);
mpf_init(x);
mpf_set_d(x, (double) 0.01);
value = mpf_get_str(NULL, &exponent, base, sigfigs, x);
if (strncmp(value, (char *) "", 1) > 0) {
if (exponent > 0) {
s_whole = malloc(exponent);
strncpy(s_whole, value, exponent);
printf("%s", s_whole);
}
value += exponent;
if (strlen(value) > 0) printf(".%s\n", value);
}
mpf_clear(x);
return 0;
}
For the wrapper, I'd ideally like to return the base, the whole component,
and the decimal component. mpf_get_str seems to be the only way to do this,
but I'm having very little luck. mpf_get_d_2exp doesn't seem like it will
help particularly, since one of the reasons for wrapping GNU MP in the first
place was to avoid a loss of precision. If I multiplied things out to get
the components I want, there would be a loss of precision, as well as speed.
Help?
Thank you for your time in advance.
Rob
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://gmplib.org/list-archives/gmp-discuss/attachments/20070919/2deec264/attachment.html
More information about the gmp-discuss
mailing list