Ver código fonte

math: tweak the real number printing routine.

By adding a bias we ensure that 1.999… will be displayed as 2.0 as long as we
do not ask for too many digits, and that rounding is reasonable for most values.
Note that our need for proper rounding is not as high as for IEEE floats since
we have an insane amount of digits at our disposal.

Also we now get rid of trailing zeroes when printing reals.
legacy
Sam Hocevar 7 anos atrás
pai
commit
1733d0ffd8
1 arquivos alterados com 11 adições e 0 exclusões
  1. +11
    -0
      src/math/real.cpp

+ 11
- 0
src/math/real.cpp Ver arquivo

@@ -1468,9 +1468,16 @@ template<> void real::sprintf(char *str, int ndigits) const

/* Normalise x so that mantissa is in [1..9.999] */
/* FIXME: better use int64_t when the cast is implemented */
/* FIXME: does not work with R_MAX and probably R_MIN */
int exponent = ceil(log10(x));
x *= pow(R_10(), -(real)exponent);

if (ndigits < 1)
ndigits = 1;

/* Add a bias to simulate some naive rounding */
x += real(4.99f) * pow(R_10(), -(real)(ndigits + 1));

if (x < R_1())
{
x *= R_10();
@@ -1488,6 +1495,10 @@ template<> void real::sprintf(char *str, int ndigits) const
x *= R_10();
}

/* Remove excess trailing zeroes */
while (str[-1] == '0' && str[-2] != '.')
--str;

/* Print exponent information */
if (exponent)
str += std::sprintf(str, "e%c%i",


Carregando…
Cancelar
Salvar