Pregunta
Estoy tratando de almacenar el valor de 0,9999 en una variable mpfr_t usando la función mpfr_set_str ()
Pero 0,9999 se redondea a 1 (o algún otro valor! = 0,9999) durante el almacenamiento, sin importar el valor ronda (GMP_RNDD, GMP_RNDU, GMP_RNDN, GMP_RNDZ)
Entonces, ¿cuál es el mejor método para almacenar en una variable de 0,9999 mpfr_t usando mpfr_set_str ()? ¿Es posible?
Aquí está mi programa de prueba, se imprime "buffer es: 1", en lugar de la querían "buffer es: 0,9999":
int main()
{
size_t precision = 4;
mpfr_t mpfrValue;
mpfr_init2(mpfrValue, precision);
mpfr_set_str(mpfrValue, "0.9999", 10, GMP_RNDN);
char *buffer = (char*)malloc((sizeof(char) * precision) + 3);
mp_exp_t exponent;
mpfr_get_str(buffer,
&exponent,
10,
precision,
mpfrValue,
GMP_RNDN);
printf("buffer is: %s\n", buffer);
free(buffer);
mpfr_clear(mpfrValue);
return 0;
}
Gracias por la ayuda
Solución
precisión es dada en bits , no en decimal dígitos, como usted parece estar asumiendo. Parece que puede volver a imprimir el valor correcto de 4 dígitos decimales con 15 bits de precisión. Además, se puede utilizar directamente la salida mpfr_printf.
Si es necesario utilizar mpfr_get_str, me gustaría pasar null como el primer parámetro. Si lo hace que la cadena se asigna para usted. Entonces, para liberarla de llamar mpfr_free_str.
int main()
{
size_t precision = 15;
mpfr_t mpfrValue;
mpfr_init2(mpfrValue, precision);
mpfr_set_str(mpfrValue, "0.9999", 10, GMP_RNDN);
mpfr_printf("Value is: %Rf\n", mpfrValue);
mpfr_clear(mpfrValue);
return 0;
}