[34b9299] | 1 | /*
|
---|
| 2 | * Copyright (c) 2012 Adam Hraska
|
---|
| 3 | * All rights reserved.
|
---|
| 4 | *
|
---|
| 5 | * Redistribution and use in source and binary forms, with or without
|
---|
| 6 | * modification, are permitted provided that the following conditions
|
---|
| 7 | * are met:
|
---|
| 8 | *
|
---|
| 9 | * - Redistributions of source code must retain the above copyright
|
---|
| 10 | * notice, this list of conditions and the following disclaimer.
|
---|
| 11 | * - Redistributions in binary form must reproduce the above copyright
|
---|
| 12 | * notice, this list of conditions and the following disclaimer in the
|
---|
| 13 | * documentation and/or other materials provided with the distribution.
|
---|
| 14 | * - The name of the author may not be used to endorse or promote products
|
---|
| 15 | * derived from this software without specific prior written permission.
|
---|
| 16 | *
|
---|
| 17 | * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
|
---|
| 18 | * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
---|
| 19 | * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
---|
| 20 | * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
|
---|
| 21 | * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
---|
| 22 | * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
---|
| 23 | * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
---|
| 24 | * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
---|
| 25 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
|
---|
| 26 | * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
---|
| 27 | */
|
---|
[82d062d8] | 28 |
|
---|
[34b9299] | 29 | #include <double_to_str.h>
|
---|
| 30 |
|
---|
| 31 | #include "private/power_of_ten.h"
|
---|
| 32 | #include <ieee_double.h>
|
---|
| 33 |
|
---|
[16bfcd3] | 34 | #include <limits.h>
|
---|
[34b9299] | 35 | #include <stdint.h>
|
---|
[3e6a98c5] | 36 | #include <stdbool.h>
|
---|
[582a0b8] | 37 | #include <stddef.h>
|
---|
| 38 | #include <assert.h>
|
---|
[34b9299] | 39 |
|
---|
| 40 | /*
|
---|
| 41 | * Floating point numbers are converted from their binary representation
|
---|
| 42 | * into a decimal string using the algorithm described in:
|
---|
| 43 | * Printing floating-point numbers quickly and accurately with integers
|
---|
| 44 | * Loitsch, 2010
|
---|
| 45 | */
|
---|
| 46 |
|
---|
| 47 | /** The computation assumes a significand of 64 bits. */
|
---|
| 48 | static const int significand_width = 64;
|
---|
| 49 |
|
---|
| 50 | /* Scale exponents to interval [alpha, gamma] to simplify conversion. */
|
---|
| 51 | static const int alpha = -59;
|
---|
| 52 | static const int gamma = -32;
|
---|
| 53 |
|
---|
| 54 | /** Returns true if the most-significant bit of num.significand is set. */
|
---|
| 55 | static bool is_normalized(fp_num_t num)
|
---|
| 56 | {
|
---|
[3bacee1] | 57 | assert(8 * sizeof(num.significand) == significand_width);
|
---|
[34b9299] | 58 |
|
---|
| 59 | /* Normalized == most significant bit of the significand is set. */
|
---|
| 60 | return (num.significand & (1ULL << (significand_width - 1))) != 0;
|
---|
| 61 | }
|
---|
| 62 |
|
---|
| 63 | /** Returns a normalized num with the MSbit set. */
|
---|
| 64 | static fp_num_t normalize(fp_num_t num)
|
---|
| 65 | {
|
---|
| 66 | const uint64_t top10bits = 0xffc0000000000000ULL;
|
---|
| 67 |
|
---|
| 68 | /* num usually comes from ieee_double with top 10 bits zero. */
|
---|
| 69 | while (0 == (num.significand & top10bits)) {
|
---|
| 70 | num.significand <<= 10;
|
---|
| 71 | num.exponent -= 10;
|
---|
| 72 | }
|
---|
| 73 |
|
---|
| 74 | while (!is_normalized(num)) {
|
---|
| 75 | num.significand <<= 1;
|
---|
| 76 | --num.exponent;
|
---|
| 77 | }
|
---|
| 78 |
|
---|
| 79 | return num;
|
---|
| 80 | }
|
---|
| 81 |
|
---|
| 82 | /** Returns x * y with an error of less than 0.5 ulp. */
|
---|
| 83 | static fp_num_t multiply(fp_num_t x, fp_num_t y)
|
---|
| 84 | {
|
---|
| 85 | assert(/* is_normalized(x) && */ is_normalized(y));
|
---|
[a35b458] | 86 |
|
---|
[34b9299] | 87 | const uint32_t low_bits = -1;
|
---|
| 88 |
|
---|
| 89 | uint64_t a, b, c, d;
|
---|
| 90 | a = x.significand >> 32;
|
---|
| 91 | b = x.significand & low_bits;
|
---|
| 92 | c = y.significand >> 32;
|
---|
| 93 | d = y.significand & low_bits;
|
---|
| 94 |
|
---|
| 95 | uint64_t bd, ad, bc, ac;
|
---|
| 96 | bd = b * d;
|
---|
| 97 | ad = a * d;
|
---|
[a35b458] | 98 |
|
---|
[34b9299] | 99 | bc = b * c;
|
---|
| 100 | ac = a * c;
|
---|
| 101 |
|
---|
[7c3fb9b] | 102 | /*
|
---|
| 103 | * Denote 32 bit parts of x a y as: x == a b, y == c d. Then:
|
---|
[1b20da0] | 104 | * a b
|
---|
[34b9299] | 105 | * * c d
|
---|
| 106 | * ----------
|
---|
| 107 | * ad bd .. multiplication of 32bit parts results in 64bit parts
|
---|
| 108 | * + ac bc
|
---|
| 109 | * ----------
|
---|
| 110 | * [b|d] .. Depicts 64 bit intermediate results and how
|
---|
| 111 | * [a|d] the 32 bit parts of these results overlap and
|
---|
| 112 | * [b|c] contribute to the final result.
|
---|
| 113 | * +[a|c]
|
---|
| 114 | * ----------
|
---|
| 115 | * [ret]
|
---|
| 116 | * [tmp]
|
---|
| 117 | */
|
---|
| 118 | uint64_t tmp = (bd >> 32) + (ad & low_bits) + (bc & low_bits);
|
---|
| 119 |
|
---|
| 120 | /* Round upwards. */
|
---|
| 121 | tmp += 1U << 31;
|
---|
| 122 |
|
---|
| 123 | fp_num_t ret;
|
---|
| 124 | ret.significand = ac + (bc >> 32) + (ad >> 32) + (tmp >> 32);
|
---|
| 125 | ret.exponent = x.exponent + y.exponent + significand_width;
|
---|
[a35b458] | 126 |
|
---|
[1b20da0] | 127 | return ret;
|
---|
[34b9299] | 128 | }
|
---|
| 129 |
|
---|
| 130 | /** Returns a - b. Both must have the same exponent. */
|
---|
| 131 | static fp_num_t subtract(fp_num_t a, fp_num_t b)
|
---|
| 132 | {
|
---|
| 133 | assert(a.exponent == b.exponent);
|
---|
| 134 | assert(a.significand >= b.significand);
|
---|
| 135 |
|
---|
| 136 | fp_num_t result;
|
---|
[a35b458] | 137 |
|
---|
[34b9299] | 138 | result.significand = a.significand - b.significand;
|
---|
| 139 | result.exponent = a.exponent;
|
---|
| 140 |
|
---|
| 141 | return result;
|
---|
| 142 | }
|
---|
| 143 |
|
---|
| 144 | /** Returns the interval [low, high] of numbers that convert to binary val. */
|
---|
[1b20da0] | 145 | static void get_normalized_bounds(ieee_double_t val, fp_num_t *high,
|
---|
[3bacee1] | 146 | fp_num_t *low, fp_num_t *val_dist)
|
---|
[34b9299] | 147 | {
|
---|
[1b20da0] | 148 | /*
|
---|
[34b9299] | 149 | * Only works if val comes directly from extract_ieee_double without
|
---|
[1b20da0] | 150 | * being manipulated in any way (eg it must not be normalized).
|
---|
[34b9299] | 151 | */
|
---|
| 152 | assert(!is_normalized(val.pos_val));
|
---|
| 153 |
|
---|
| 154 | high->significand = (val.pos_val.significand << 1) + 1;
|
---|
| 155 | high->exponent = val.pos_val.exponent - 1;
|
---|
| 156 |
|
---|
| 157 | /* val_dist = high - val */
|
---|
| 158 | val_dist->significand = 1;
|
---|
| 159 | val_dist->exponent = val.pos_val.exponent - 1;
|
---|
| 160 |
|
---|
| 161 | /* Distance from both lower and upper bound is the same. */
|
---|
| 162 | if (!val.is_accuracy_step) {
|
---|
| 163 | low->significand = (val.pos_val.significand << 1) - 1;
|
---|
| 164 | low->exponent = val.pos_val.exponent - 1;
|
---|
| 165 | } else {
|
---|
| 166 | low->significand = (val.pos_val.significand << 2) - 1;
|
---|
| 167 | low->exponent = val.pos_val.exponent - 2;
|
---|
| 168 | }
|
---|
| 169 |
|
---|
| 170 | *high = normalize(*high);
|
---|
| 171 |
|
---|
[1b20da0] | 172 | /*
|
---|
[34b9299] | 173 | * Lower bound may not be normalized if subtracting 1 unit
|
---|
[1b20da0] | 174 | * reset the most-significant bit to 0.
|
---|
[34b9299] | 175 | */
|
---|
| 176 | low->significand = low->significand << (low->exponent - high->exponent);
|
---|
| 177 | low->exponent = high->exponent;
|
---|
| 178 |
|
---|
[1b20da0] | 179 | val_dist->significand =
|
---|
[3bacee1] | 180 | val_dist->significand << (val_dist->exponent - high->exponent);
|
---|
[34b9299] | 181 | val_dist->exponent = high->exponent;
|
---|
| 182 | }
|
---|
| 183 |
|
---|
[1b20da0] | 184 | /** Determines the interval of numbers that have the binary representation
|
---|
[34b9299] | 185 | * of val.
|
---|
[1b20da0] | 186 | *
|
---|
[34b9299] | 187 | * Numbers in the range [scaled_upper_bound - bounds_delta, scaled_upper_bound]
|
---|
[1b20da0] | 188 | * have the same double binary representation as val.
|
---|
[34b9299] | 189 | *
|
---|
| 190 | * Bounds are scaled by 10^scale so that alpha <= exponent <= gamma.
|
---|
| 191 | * Moreover, scaled_upper_bound is normalized.
|
---|
| 192 | *
|
---|
| 193 | * val_dist is the scaled distance from val to the upper bound, ie
|
---|
| 194 | * val_dist == (upper_bound - val) * 10^scale
|
---|
| 195 | */
|
---|
[1b20da0] | 196 | static void calc_scaled_bounds(ieee_double_t val, fp_num_t *scaled_upper_bound,
|
---|
[3bacee1] | 197 | fp_num_t *bounds_delta, fp_num_t *val_dist, int *scale)
|
---|
[34b9299] | 198 | {
|
---|
| 199 | fp_num_t upper_bound, lower_bound;
|
---|
| 200 |
|
---|
| 201 | get_normalized_bounds(val, &upper_bound, &lower_bound, val_dist);
|
---|
| 202 |
|
---|
| 203 | assert(upper_bound.exponent == lower_bound.exponent);
|
---|
| 204 | assert(is_normalized(upper_bound));
|
---|
| 205 | assert(normalize(val.pos_val).exponent == upper_bound.exponent);
|
---|
| 206 |
|
---|
[1b20da0] | 207 | /*
|
---|
[34b9299] | 208 | * Find such a cached normalized power of 10 that if multiplied
|
---|
[1b20da0] | 209 | * by upper_bound the binary exponent of upper_bound almost vanishes,
|
---|
[34b9299] | 210 | * ie:
|
---|
| 211 | * upper_scaled := upper_bound * 10^scale
|
---|
| 212 | * alpha <= upper_scaled.exponent <= gamma
|
---|
| 213 | * alpha <= upper_bound.exponent + pow_10.exponent + 64 <= gamma
|
---|
| 214 | */
|
---|
| 215 | fp_num_t scaling_power_of_10;
|
---|
| 216 | int lower_bin_exp = alpha - upper_bound.exponent - significand_width;
|
---|
| 217 |
|
---|
| 218 | get_power_of_ten(lower_bin_exp, &scaling_power_of_10, scale);
|
---|
| 219 |
|
---|
| 220 | int scale_exp = scaling_power_of_10.exponent;
|
---|
| 221 | assert(alpha <= upper_bound.exponent + scale_exp + significand_width);
|
---|
| 222 | assert(upper_bound.exponent + scale_exp + significand_width <= gamma);
|
---|
| 223 |
|
---|
| 224 | fp_num_t upper_scaled = multiply(upper_bound, scaling_power_of_10);
|
---|
| 225 | fp_num_t lower_scaled = multiply(lower_bound, scaling_power_of_10);
|
---|
| 226 | *val_dist = multiply(*val_dist, scaling_power_of_10);
|
---|
| 227 |
|
---|
| 228 | assert(alpha <= upper_scaled.exponent && upper_scaled.exponent <= gamma);
|
---|
| 229 |
|
---|
[1b20da0] | 230 | /*
|
---|
[34b9299] | 231 | * Any value between lower and upper bound would be represented
|
---|
| 232 | * in binary as the double val originated from. The bounds were
|
---|
[1b20da0] | 233 | * however scaled by an imprecise power of 10 (error less than
|
---|
| 234 | * 1 ulp) so the scaled bounds have an error of less than 1 ulp.
|
---|
| 235 | * Conservatively round the lower bound up and the upper bound
|
---|
[34b9299] | 236 | * down by 1 ulp just to be on the safe side. It avoids pronouncing
|
---|
| 237 | * produced decimal digits as correct if such a decimal number
|
---|
[1b20da0] | 238 | * is close to the bounds to within 1 ulp.
|
---|
[34b9299] | 239 | */
|
---|
| 240 | upper_scaled.significand -= 1;
|
---|
| 241 | lower_scaled.significand += 1;
|
---|
| 242 |
|
---|
| 243 | *bounds_delta = subtract(upper_scaled, lower_scaled);
|
---|
| 244 | *scaled_upper_bound = upper_scaled;
|
---|
| 245 | }
|
---|
| 246 |
|
---|
[d1582b50] | 247 | /** Rounds the last digit of buf so that it is closest to the converted number. */
|
---|
[34b9299] | 248 | static void round_last_digit(uint64_t rest, uint64_t w_dist, uint64_t delta,
|
---|
[3bacee1] | 249 | uint64_t digit_val_diff, char *buf, int len)
|
---|
[34b9299] | 250 | {
|
---|
| 251 | /*
|
---|
| 252 | * | <------- delta -------> |
|
---|
| 253 | * | | <---- w_dist ----> |
|
---|
| 254 | * | | | <- rest -> |
|
---|
| 255 | * | | | |
|
---|
| 256 | * | | ` buffer |
|
---|
| 257 | * | ` w ` upper
|
---|
| 258 | * ` lower
|
---|
| 259 | *
|
---|
| 260 | * delta = upper - lower .. conservative/safe interval
|
---|
[1b20da0] | 261 | * w_dist = upper - w
|
---|
[34b9299] | 262 | * upper = "number represented by digits in buf" + rest
|
---|
[1b20da0] | 263 | *
|
---|
| 264 | * Changing buf[len - 1] changes the value represented by buf
|
---|
[34b9299] | 265 | * by digit_val_diff * scaling, where scaling is shared by
|
---|
[1b20da0] | 266 | * all parameters.
|
---|
[34b9299] | 267 | *
|
---|
| 268 | */
|
---|
| 269 |
|
---|
| 270 | /* Current number in buf is greater than the double being converted */
|
---|
| 271 | bool cur_greater_w = rest < w_dist;
|
---|
| 272 | /* Rounding down by one would keep buf in between bounds (in safe rng). */
|
---|
| 273 | bool next_in_val_rng = cur_greater_w && (rest + digit_val_diff < delta);
|
---|
| 274 | /* Rounding down by one would bring buf closer to the processed number. */
|
---|
[3bacee1] | 275 | bool next_closer = next_in_val_rng &&
|
---|
| 276 | (rest + digit_val_diff < w_dist || rest - w_dist < w_dist - rest);
|
---|
[34b9299] | 277 |
|
---|
[7c3fb9b] | 278 | /*
|
---|
| 279 | * Of the shortest strings pick the one that is closest to the actual
|
---|
| 280 | * floating point number.
|
---|
| 281 | */
|
---|
[34b9299] | 282 | while (next_closer) {
|
---|
| 283 | assert('0' < buf[len - 1]);
|
---|
| 284 | assert(0 < digit_val_diff);
|
---|
| 285 |
|
---|
| 286 | --buf[len - 1];
|
---|
| 287 | rest += digit_val_diff;
|
---|
| 288 |
|
---|
| 289 | cur_greater_w = rest < w_dist;
|
---|
| 290 | next_in_val_rng = cur_greater_w && (rest + digit_val_diff < delta);
|
---|
[3bacee1] | 291 | next_closer = next_in_val_rng &&
|
---|
| 292 | (rest + digit_val_diff < w_dist || rest - w_dist < w_dist - rest);
|
---|
[34b9299] | 293 | }
|
---|
| 294 | }
|
---|
| 295 |
|
---|
| 296 | /** Generates the shortest accurate decimal string representation.
|
---|
| 297 | *
|
---|
[1b20da0] | 298 | * Outputs (mostly) the shortest accurate string representation
|
---|
[34b9299] | 299 | * for the number scaled_upper - val_dist. Numbers in the interval
|
---|
| 300 | * [scaled_upper - delta, scaled_upper] have the same binary
|
---|
| 301 | * floating point representation and will therefore share the
|
---|
| 302 | * shortest string representation (up to the rounding of the last
|
---|
| 303 | * digit to bring the shortest string also the closest to the
|
---|
[1b20da0] | 304 | * actual number).
|
---|
[34b9299] | 305 | *
|
---|
| 306 | * @param scaled_upper Scaled upper bound of numbers that have the
|
---|
| 307 | * same binary representation as the converted number.
|
---|
| 308 | * Scaled by 10^-scale so that alpha <= exponent <= gamma.
|
---|
| 309 | * @param delta scaled_upper - delta is the lower bound of numbers
|
---|
| 310 | * that share the same binary representation in double.
|
---|
| 311 | * @param val_dist scaled_upper - val_dist is the number whose
|
---|
| 312 | * decimal string we're generating.
|
---|
| 313 | * @param scale Decimal scaling of the value to convert (ie scaled_upper).
|
---|
[1b20da0] | 314 | * @param buf Buffer to store the string representation. Must be large
|
---|
[34b9299] | 315 | * enough to store all digits and a null terminator. At most
|
---|
| 316 | * MAX_DOUBLE_STR_LEN digits will be written (not counting
|
---|
| 317 | * the null terminator).
|
---|
[1b20da0] | 318 | * @param buf_size Size of buf in bytes.
|
---|
| 319 | * @param dec_exponent Will be set to the decimal exponent of the number
|
---|
[34b9299] | 320 | * string in buf.
|
---|
| 321 | *
|
---|
| 322 | * @return Number of digits; negative on failure (eg buffer too small).
|
---|
| 323 | */
|
---|
[1b20da0] | 324 | static int gen_dec_digits(fp_num_t scaled_upper, fp_num_t delta,
|
---|
[3bacee1] | 325 | fp_num_t val_dist, int scale, char *buf, size_t buf_size, int *dec_exponent)
|
---|
[34b9299] | 326 | {
|
---|
[1b20da0] | 327 | /*
|
---|
| 328 | * The integral part of scaled_upper is 5 to 32 bits long while
|
---|
[34b9299] | 329 | * the remaining fractional part is 59 to 32 bits long because:
|
---|
| 330 | * -59 == alpha <= scaled_upper.e <= gamma == -32
|
---|
| 331 | *
|
---|
| 332 | * | <------- delta -------> |
|
---|
| 333 | * | | <--- val_dist ---> |
|
---|
| 334 | * | | |<- remainder ->|
|
---|
| 335 | * | | | |
|
---|
| 336 | * | | ` buffer |
|
---|
| 337 | * | ` val ` upper
|
---|
| 338 | * ` lower
|
---|
| 339 | *
|
---|
[1b20da0] | 340 | */
|
---|
[34b9299] | 341 | assert(scaled_upper.significand != 0);
|
---|
| 342 | assert(alpha <= scaled_upper.exponent && scaled_upper.exponent <= gamma);
|
---|
| 343 | assert(scaled_upper.exponent == delta.exponent);
|
---|
| 344 | assert(scaled_upper.exponent == val_dist.exponent);
|
---|
| 345 | assert(val_dist.significand <= delta.significand);
|
---|
| 346 |
|
---|
| 347 | /* We'll produce at least one digit and a null terminator. */
|
---|
| 348 | if (buf_size < 2) {
|
---|
| 349 | return -1;
|
---|
| 350 | }
|
---|
| 351 |
|
---|
| 352 | /* one is number 1 encoded with the same exponent as scaled_upper */
|
---|
| 353 | fp_num_t one;
|
---|
| 354 | one.significand = ((uint64_t) 1) << (-scaled_upper.exponent);
|
---|
| 355 | one.exponent = scaled_upper.exponent;
|
---|
| 356 |
|
---|
| 357 | /*
|
---|
[1b20da0] | 358 | * Extract the integral part of scaled_upper.
|
---|
| 359 | * upper / one == upper >> -one.e
|
---|
[34b9299] | 360 | */
|
---|
| 361 | uint32_t int_part = (uint32_t)(scaled_upper.significand >> (-one.exponent));
|
---|
[a35b458] | 362 |
|
---|
[1b20da0] | 363 | /*
|
---|
[34b9299] | 364 | * Fractional part of scaled_upper.
|
---|
[1b20da0] | 365 | * upper % one == upper & (one.f - 1)
|
---|
[34b9299] | 366 | */
|
---|
| 367 | uint64_t frac_part = scaled_upper.significand & (one.significand - 1);
|
---|
| 368 |
|
---|
| 369 | /*
|
---|
[1b20da0] | 370 | * The integral part of upper has at least 5 bits (64 + alpha) and
|
---|
| 371 | * at most 32 bits (64 + gamma). The integral part has at most 10
|
---|
| 372 | * decimal digits, so kappa <= 10.
|
---|
[34b9299] | 373 | */
|
---|
| 374 | int kappa = 10;
|
---|
| 375 | uint32_t div = 1000000000;
|
---|
| 376 | size_t len = 0;
|
---|
| 377 |
|
---|
| 378 | /* Produce decimal digits for the integral part of upper. */
|
---|
| 379 | while (kappa > 0) {
|
---|
| 380 | int digit = int_part / div;
|
---|
| 381 | int_part %= div;
|
---|
| 382 |
|
---|
| 383 | --kappa;
|
---|
| 384 |
|
---|
| 385 | /* Skip leading zeros. */
|
---|
| 386 | if (digit != 0 || len != 0) {
|
---|
| 387 | /* Current length + new digit + null terminator <= buf_size */
|
---|
| 388 | if (len + 2 <= buf_size) {
|
---|
| 389 | buf[len] = '0' + digit;
|
---|
| 390 | ++len;
|
---|
| 391 | } else {
|
---|
| 392 | return -1;
|
---|
| 393 | }
|
---|
| 394 | }
|
---|
| 395 |
|
---|
[1b20da0] | 396 | /*
|
---|
[34b9299] | 397 | * Difference between the so far produced decimal number and upper
|
---|
[1b20da0] | 398 | * is calculated as: remaining_int_part * one + frac_part
|
---|
[34b9299] | 399 | */
|
---|
| 400 | uint64_t remainder = (((uint64_t)int_part) << -one.exponent) + frac_part;
|
---|
| 401 |
|
---|
| 402 | /* The produced decimal number would convert back to upper. */
|
---|
| 403 | if (remainder <= delta.significand) {
|
---|
| 404 | assert(0 < len && len < buf_size);
|
---|
| 405 | *dec_exponent = kappa - scale;
|
---|
| 406 | buf[len] = '\0';
|
---|
| 407 |
|
---|
| 408 | /* Of the shortest representations choose the numerically closest. */
|
---|
| 409 | round_last_digit(remainder, val_dist.significand, delta.significand,
|
---|
[3bacee1] | 410 | (uint64_t)div << (-one.exponent), buf, len);
|
---|
[34b9299] | 411 | return len;
|
---|
| 412 | }
|
---|
| 413 |
|
---|
| 414 | div /= 10;
|
---|
| 415 | }
|
---|
| 416 |
|
---|
| 417 | /* Generate decimal digits for the fractional part of upper. */
|
---|
| 418 | do {
|
---|
| 419 | /*
|
---|
| 420 | * Does not overflow because at least 5 upper bits were
|
---|
[1b20da0] | 421 | * taken by the integral part and are now unused in frac_part.
|
---|
[34b9299] | 422 | */
|
---|
| 423 | frac_part *= 10;
|
---|
| 424 | delta.significand *= 10;
|
---|
| 425 | val_dist.significand *= 10;
|
---|
| 426 |
|
---|
| 427 | /* frac_part / one */
|
---|
| 428 | int digit = (int)(frac_part >> (-one.exponent));
|
---|
[a35b458] | 429 |
|
---|
[34b9299] | 430 | /* frac_part %= one */
|
---|
| 431 | frac_part &= one.significand - 1;
|
---|
| 432 |
|
---|
| 433 | --kappa;
|
---|
| 434 |
|
---|
| 435 | /* Skip leading zeros. */
|
---|
| 436 | if (digit == 0 && len == 0) {
|
---|
| 437 | continue;
|
---|
| 438 | }
|
---|
| 439 |
|
---|
| 440 | /* Current length + new digit + null terminator <= buf_size */
|
---|
| 441 | if (len + 2 <= buf_size) {
|
---|
| 442 | buf[len] = '0' + digit;
|
---|
| 443 | ++len;
|
---|
| 444 | } else {
|
---|
| 445 | return -1;
|
---|
| 446 | }
|
---|
| 447 | } while (frac_part > delta.significand);
|
---|
| 448 |
|
---|
| 449 | assert(0 < len && len < buf_size);
|
---|
| 450 |
|
---|
| 451 | *dec_exponent = kappa - scale;
|
---|
| 452 | buf[len] = '\0';
|
---|
| 453 |
|
---|
| 454 | /* Of the shortest representations choose the numerically closest one. */
|
---|
[1b20da0] | 455 | round_last_digit(frac_part, val_dist.significand, delta.significand,
|
---|
[3bacee1] | 456 | one.significand, buf, len);
|
---|
[34b9299] | 457 |
|
---|
| 458 | return len;
|
---|
| 459 | }
|
---|
| 460 |
|
---|
| 461 | /** Produce a string for 0.0 */
|
---|
| 462 | static int zero_to_str(char *buf, size_t buf_size, int *dec_exponent)
|
---|
| 463 | {
|
---|
| 464 | if (2 <= buf_size) {
|
---|
| 465 | buf[0] = '0';
|
---|
| 466 | buf[1] = '\0';
|
---|
| 467 | *dec_exponent = 0;
|
---|
| 468 | return 1;
|
---|
| 469 | } else {
|
---|
| 470 | return -1;
|
---|
| 471 | }
|
---|
| 472 | }
|
---|
| 473 |
|
---|
[1b20da0] | 474 | /** Converts a non-special double into its shortest accurate string
|
---|
[34b9299] | 475 | * representation.
|
---|
| 476 | *
|
---|
[1b20da0] | 477 | * Produces an accurate string representation, ie the string will
|
---|
[34b9299] | 478 | * convert back to the same binary double (eg via strtod). In the
|
---|
| 479 | * vast majority of cases (99%) the string will be the shortest such
|
---|
| 480 | * string that is also the closest to the value of any shortest
|
---|
| 481 | * string representations. Therefore, no trailing zeros are ever
|
---|
| 482 | * produced.
|
---|
| 483 | *
|
---|
| 484 | * Conceptually, the value is: buf * 10^dec_exponent
|
---|
| 485 | *
|
---|
| 486 | * Never outputs trailing zeros.
|
---|
| 487 | *
|
---|
| 488 | * @param ieee_val Binary double description to convert. Must be the product
|
---|
| 489 | * of extract_ieee_double and it must not be a special number.
|
---|
[1b20da0] | 490 | * @param buf Buffer to store the string representation. Must be large
|
---|
[34b9299] | 491 | * enough to store all digits and a null terminator. At most
|
---|
| 492 | * MAX_DOUBLE_STR_LEN digits will be written (not counting
|
---|
| 493 | * the null terminator).
|
---|
| 494 | * @param buf_size Size of buf in bytes.
|
---|
[1b20da0] | 495 | * @param dec_exponent Will be set to the decimal exponent of the number
|
---|
[34b9299] | 496 | * string in buf.
|
---|
| 497 | *
|
---|
| 498 | * @return The number of printed digits. A negative value indicates
|
---|
| 499 | * an error: buf too small (or ieee_val.is_special).
|
---|
| 500 | */
|
---|
[1b20da0] | 501 | int double_to_short_str(ieee_double_t ieee_val, char *buf, size_t buf_size,
|
---|
[3bacee1] | 502 | int *dec_exponent)
|
---|
[34b9299] | 503 | {
|
---|
| 504 | /* The whole computation assumes 64bit significand. */
|
---|
[0a520db] | 505 | static_assert(sizeof(ieee_val.pos_val.significand) == sizeof(uint64_t), "");
|
---|
[34b9299] | 506 |
|
---|
| 507 | if (ieee_val.is_special) {
|
---|
| 508 | return -1;
|
---|
| 509 | }
|
---|
| 510 |
|
---|
| 511 | /* Zero cannot be normalized. Handle it here. */
|
---|
| 512 | if (0 == ieee_val.pos_val.significand) {
|
---|
| 513 | return zero_to_str(buf, buf_size, dec_exponent);
|
---|
| 514 | }
|
---|
| 515 |
|
---|
| 516 | fp_num_t scaled_upper_bound;
|
---|
| 517 | fp_num_t delta;
|
---|
| 518 | fp_num_t val_dist;
|
---|
| 519 | int scale;
|
---|
| 520 |
|
---|
[1b20da0] | 521 | calc_scaled_bounds(ieee_val, &scaled_upper_bound,
|
---|
[3bacee1] | 522 | &delta, &val_dist, &scale);
|
---|
[34b9299] | 523 |
|
---|
[1b20da0] | 524 | int len = gen_dec_digits(scaled_upper_bound, delta, val_dist, scale,
|
---|
[3bacee1] | 525 | buf, buf_size, dec_exponent);
|
---|
[34b9299] | 526 |
|
---|
| 527 | assert(len <= MAX_DOUBLE_STR_LEN);
|
---|
| 528 | return len;
|
---|
| 529 | }
|
---|
| 530 |
|
---|
| 531 | /** Generates a fixed number of decimal digits of w_scaled.
|
---|
| 532 | *
|
---|
| 533 | * double == w_scaled * 10^-scale, where alpha <= w_scaled.e <= gamma
|
---|
| 534 | *
|
---|
| 535 | * @param w_scaled Scaled number by 10^-scale so that
|
---|
| 536 | * alpha <= exponent <= gamma
|
---|
| 537 | * @param scale Decimal scaling of the value to convert (ie w_scaled).
|
---|
[1b20da0] | 538 | * @param signif_d_cnt Maximum number of significant digits to output.
|
---|
[34b9299] | 539 | * Negative if as many as possible are requested.
|
---|
| 540 | * @param frac_d_cnt Maximum number of fractional digits to output.
|
---|
| 541 | * Negative if as many as possible are requested.
|
---|
| 542 | * Eg. if 2 then 1.234 -> "1.23"; if 2 then 3e-9 -> "0".
|
---|
[1b20da0] | 543 | * @param buf Buffer to store the string representation. Must be large
|
---|
[34b9299] | 544 | * enough to store all digits and a null terminator. At most
|
---|
| 545 | * MAX_DOUBLE_STR_LEN digits will be written (not counting
|
---|
| 546 | * the null terminator).
|
---|
[1b20da0] | 547 | * @param buf_size Size of buf in bytes.
|
---|
[34b9299] | 548 | *
|
---|
| 549 | * @return Number of digits; negative on failure (eg buffer too small).
|
---|
| 550 | */
|
---|
[1b20da0] | 551 | static int gen_fixed_dec_digits(fp_num_t w_scaled, int scale, int signif_d_cnt,
|
---|
[3bacee1] | 552 | int frac_d_cnt, char *buf, size_t buf_size, int *dec_exponent)
|
---|
[34b9299] | 553 | {
|
---|
| 554 | /* We'll produce at least one digit and a null terminator. */
|
---|
| 555 | if (0 == signif_d_cnt || buf_size < 2) {
|
---|
| 556 | return -1;
|
---|
| 557 | }
|
---|
| 558 |
|
---|
[1b20da0] | 559 | /*
|
---|
| 560 | * The integral part of w_scaled is 5 to 32 bits long while the
|
---|
[34b9299] | 561 | * remaining fractional part is 59 to 32 bits long because:
|
---|
| 562 | * -59 == alpha <= w_scaled.e <= gamma == -32
|
---|
[1b20da0] | 563 | *
|
---|
[34b9299] | 564 | * Therefore:
|
---|
| 565 | * | 5..32 bits | 32..59 bits | == w_scaled == w * 10^scale
|
---|
| 566 | * | int_part | frac_part |
|
---|
| 567 | * |0 0 .. 0 1|0 0 .. 0 0| == one == 1.0
|
---|
[1b20da0] | 568 | * | 0 |0 0 .. 0 1| == w_err == 1 * 2^w_scaled.e
|
---|
[7c3fb9b] | 569 | */
|
---|
[34b9299] | 570 | assert(alpha <= w_scaled.exponent && w_scaled.exponent <= gamma);
|
---|
| 571 | assert(0 != w_scaled.significand);
|
---|
| 572 |
|
---|
[1b20da0] | 573 | /*
|
---|
[34b9299] | 574 | * Scaling the number being converted by 10^scale introduced
|
---|
| 575 | * an error of less that 1 ulp. The actual value of w_scaled
|
---|
[1b20da0] | 576 | * could lie anywhere between w_scaled.signif +/- w_err.
|
---|
[34b9299] | 577 | * Scale the error locally as we scale the fractional part
|
---|
| 578 | * of w_scaled.
|
---|
| 579 | */
|
---|
| 580 | uint64_t w_err = 1;
|
---|
| 581 |
|
---|
| 582 | /* one is number 1.0 encoded with the same exponent as w_scaled */
|
---|
| 583 | fp_num_t one;
|
---|
| 584 | one.significand = ((uint64_t) 1) << (-w_scaled.exponent);
|
---|
| 585 | one.exponent = w_scaled.exponent;
|
---|
| 586 |
|
---|
[7c3fb9b] | 587 | /*
|
---|
| 588 | * Extract the integral part of w_scaled.
|
---|
| 589 | * w_scaled / one == w_scaled >> -one.e
|
---|
| 590 | */
|
---|
[34b9299] | 591 | uint32_t int_part = (uint32_t)(w_scaled.significand >> (-one.exponent));
|
---|
| 592 |
|
---|
[7c3fb9b] | 593 | /*
|
---|
| 594 | * Fractional part of w_scaled.
|
---|
| 595 | * w_scaled % one == w_scaled & (one.f - 1)
|
---|
| 596 | */
|
---|
[34b9299] | 597 | uint64_t frac_part = w_scaled.significand & (one.significand - 1);
|
---|
| 598 |
|
---|
| 599 | size_t len = 0;
|
---|
[1b20da0] | 600 | /*
|
---|
| 601 | * The integral part of w_scaled has at least 5 bits (64 + alpha = 5)
|
---|
| 602 | * and at most 32 bits (64 + gamma = 32). The integral part has
|
---|
| 603 | * at most 10 decimal digits, so kappa <= 10.
|
---|
[34b9299] | 604 | */
|
---|
| 605 | int kappa = 10;
|
---|
| 606 | uint32_t div = 1000000000;
|
---|
| 607 |
|
---|
| 608 | int rem_signif_d_cnt = signif_d_cnt;
|
---|
[1b20da0] | 609 | int rem_frac_d_cnt =
|
---|
[3bacee1] | 610 | (frac_d_cnt >= 0) ? (kappa - scale + frac_d_cnt) : INT_MAX;
|
---|
[34b9299] | 611 |
|
---|
| 612 | /* Produce decimal digits for the integral part of w_scaled. */
|
---|
| 613 | while (kappa > 0 && rem_signif_d_cnt != 0 && rem_frac_d_cnt > 0) {
|
---|
| 614 | int digit = int_part / div;
|
---|
| 615 | int_part %= div;
|
---|
| 616 |
|
---|
| 617 | div /= 10;
|
---|
| 618 | --kappa;
|
---|
| 619 | --rem_frac_d_cnt;
|
---|
| 620 |
|
---|
| 621 | /* Skip leading zeros. */
|
---|
| 622 | if (digit == 0 && len == 0) {
|
---|
| 623 | continue;
|
---|
| 624 | }
|
---|
| 625 |
|
---|
| 626 | /* Current length + new digit + null terminator <= buf_size */
|
---|
| 627 | if (len + 2 <= buf_size) {
|
---|
| 628 | buf[len] = '0' + digit;
|
---|
| 629 | ++len;
|
---|
| 630 | --rem_signif_d_cnt;
|
---|
| 631 | } else {
|
---|
| 632 | return -1;
|
---|
| 633 | }
|
---|
| 634 | }
|
---|
| 635 |
|
---|
| 636 | /* Generate decimal digits for the fractional part of w_scaled. */
|
---|
| 637 | while (w_err <= frac_part && rem_signif_d_cnt != 0 && rem_frac_d_cnt > 0) {
|
---|
| 638 | /*
|
---|
| 639 | * Does not overflow because at least 5 upper bits were
|
---|
[1b20da0] | 640 | * taken by the integral part and are now unused in frac_part.
|
---|
[34b9299] | 641 | */
|
---|
| 642 | frac_part *= 10;
|
---|
| 643 | w_err *= 10;
|
---|
| 644 |
|
---|
| 645 | /* frac_part / one */
|
---|
| 646 | int digit = (int)(frac_part >> (-one.exponent));
|
---|
[a35b458] | 647 |
|
---|
[34b9299] | 648 | /* frac_part %= one */
|
---|
| 649 | frac_part &= one.significand - 1;
|
---|
| 650 |
|
---|
| 651 | --kappa;
|
---|
| 652 | --rem_frac_d_cnt;
|
---|
| 653 |
|
---|
| 654 | /* Skip leading zeros. */
|
---|
| 655 | if (digit == 0 && len == 0) {
|
---|
| 656 | continue;
|
---|
| 657 | }
|
---|
| 658 |
|
---|
| 659 | /* Current length + new digit + null terminator <= buf_size */
|
---|
| 660 | if (len + 2 <= buf_size) {
|
---|
| 661 | buf[len] = '0' + digit;
|
---|
| 662 | ++len;
|
---|
| 663 | --rem_signif_d_cnt;
|
---|
| 664 | } else {
|
---|
| 665 | return -1;
|
---|
| 666 | }
|
---|
[850fd32] | 667 | }
|
---|
[34b9299] | 668 |
|
---|
| 669 | assert(/* 0 <= len && */ len < buf_size);
|
---|
| 670 |
|
---|
| 671 | if (0 < len) {
|
---|
| 672 | *dec_exponent = kappa - scale;
|
---|
| 673 | assert(frac_d_cnt < 0 || -frac_d_cnt <= *dec_exponent);
|
---|
| 674 | } else {
|
---|
[1b20da0] | 675 | /*
|
---|
| 676 | * The number of fractional digits was too limiting to produce
|
---|
| 677 | * any digits.
|
---|
[34b9299] | 678 | */
|
---|
| 679 | assert(rem_frac_d_cnt <= 0 || w_scaled.significand == 0);
|
---|
| 680 | *dec_exponent = 0;
|
---|
| 681 | buf[0] = '0';
|
---|
| 682 | len = 1;
|
---|
| 683 | }
|
---|
| 684 |
|
---|
| 685 | if (len < buf_size) {
|
---|
| 686 | buf[len] = '\0';
|
---|
| 687 | assert(signif_d_cnt < 0 || (int)len <= signif_d_cnt);
|
---|
| 688 | return len;
|
---|
| 689 | } else {
|
---|
| 690 | return -1;
|
---|
| 691 | }
|
---|
| 692 | }
|
---|
| 693 |
|
---|
| 694 | /** Converts a non-special double into its string representation.
|
---|
| 695 | *
|
---|
| 696 | * Conceptually, the truncated double value is: buf * 10^dec_exponent
|
---|
| 697 | *
|
---|
| 698 | * Conversion errors are tracked, so all produced digits except the
|
---|
| 699 | * last one are accurate. Garbage digits are never produced.
|
---|
[1b20da0] | 700 | * If the requested number of digits cannot be produced accurately
|
---|
| 701 | * due to conversion errors less digits are produced than requested
|
---|
[34b9299] | 702 | * and the last digit has an error of +/- 1 (so if '7' is the last
|
---|
| 703 | * converted digit it might have been converted to any of '6'..'8'
|
---|
[1b20da0] | 704 | * had the conversion been completely precise).
|
---|
[34b9299] | 705 | *
|
---|
[1b20da0] | 706 | * If no error occurs at least one digit is output.
|
---|
[34b9299] | 707 | *
|
---|
[1b20da0] | 708 | * The conversion stops once the requested number of significant or
|
---|
| 709 | * fractional digits is reached or the conversion error is too large
|
---|
[34b9299] | 710 | * to generate any more digits (whichever happens first).
|
---|
| 711 | *
|
---|
| 712 | * Any digits following the first (most-significant) digit (this digit
|
---|
| 713 | * included) are counted as significant digits; eg:
|
---|
| 714 | * 1.4, 4 signif -> "1400" * 10^-3, ie 1.400
|
---|
| 715 | * 1000.3, 1 signif -> "1" * 10^3 ie 1000
|
---|
| 716 | * 0.003, 2 signif -> "30" * 10^-4 ie 0.003
|
---|
| 717 | * 9.5 1 signif -> "9" * 10^0, ie 9
|
---|
| 718 | *
|
---|
| 719 | * Any digits following the decimal point are counted as fractional digits.
|
---|
| 720 | * This includes the zeros that would appear between the decimal point
|
---|
| 721 | * and the first non-zero fractional digit. If fewer fractional digits
|
---|
| 722 | * are requested than would allow to place the most-significant digit
|
---|
| 723 | * a "0" is output. Eg:
|
---|
| 724 | * 1.4, 3 frac -> "1400" * 10^-3, ie 1.400
|
---|
| 725 | * 12.34 4 frac -> "123400" * 10^-4, ie 12.3400
|
---|
| 726 | * 3e-99 4 frac -> "0" * 10^0, ie 0
|
---|
| 727 | * 0.009 2 frac -> "0" * 10^-2, ie 0
|
---|
| 728 | *
|
---|
| 729 | * @param ieee_val Binary double description to convert. Must be the product
|
---|
| 730 | * of extract_ieee_double and it must not be a special number.
|
---|
| 731 | * @param signif_d_cnt Maximum number of significant digits to produce.
|
---|
[1b20da0] | 732 | * The output is not rounded.
|
---|
[34b9299] | 733 | * Set to a negative value to generate as many digits
|
---|
| 734 | * as accurately possible.
|
---|
| 735 | * @param frac_d_cnt Maximum number of fractional digits to produce including
|
---|
[1b20da0] | 736 | * any zeros immediately trailing the decimal point.
|
---|
| 737 | * The output is not rounded.
|
---|
[34b9299] | 738 | * Set to a negative value to generate as many digits
|
---|
| 739 | * as accurately possible.
|
---|
[1b20da0] | 740 | * @param buf Buffer to store the string representation. Must be large
|
---|
[34b9299] | 741 | * enough to store all digits and a null terminator. At most
|
---|
| 742 | * MAX_DOUBLE_STR_LEN digits will be written (not counting
|
---|
| 743 | * the null terminator).
|
---|
| 744 | * @param buf_size Size of buf in bytes.
|
---|
[1b20da0] | 745 | * @param dec_exponent Set to the decimal exponent of the number string
|
---|
[34b9299] | 746 | * in buf.
|
---|
| 747 | *
|
---|
| 748 | * @return The number of output digits. A negative value indicates
|
---|
[1b20da0] | 749 | * an error: buf too small (or ieee_val.is_special, or
|
---|
[34b9299] | 750 | * signif_d_cnt == 0).
|
---|
| 751 | */
|
---|
| 752 | int double_to_fixed_str(ieee_double_t ieee_val, int signif_d_cnt,
|
---|
[3bacee1] | 753 | int frac_d_cnt, char *buf, size_t buf_size, int *dec_exponent)
|
---|
[34b9299] | 754 | {
|
---|
| 755 | /* The whole computation assumes 64bit significand. */
|
---|
[0a520db] | 756 | static_assert(sizeof(ieee_val.pos_val.significand) == sizeof(uint64_t), "");
|
---|
[34b9299] | 757 |
|
---|
| 758 | if (ieee_val.is_special) {
|
---|
| 759 | return -1;
|
---|
| 760 | }
|
---|
| 761 |
|
---|
| 762 | /* Zero cannot be normalized. Handle it here. */
|
---|
| 763 | if (0 == ieee_val.pos_val.significand) {
|
---|
| 764 | return zero_to_str(buf, buf_size, dec_exponent);
|
---|
| 765 | }
|
---|
| 766 |
|
---|
| 767 | /* Normalize and scale. */
|
---|
| 768 | fp_num_t w = normalize(ieee_val.pos_val);
|
---|
| 769 |
|
---|
| 770 | int lower_bin_exp = alpha - w.exponent - significand_width;
|
---|
| 771 |
|
---|
| 772 | int scale;
|
---|
| 773 | fp_num_t scaling_power_of_10;
|
---|
| 774 |
|
---|
| 775 | get_power_of_ten(lower_bin_exp, &scaling_power_of_10, &scale);
|
---|
| 776 |
|
---|
| 777 | fp_num_t w_scaled = multiply(w, scaling_power_of_10);
|
---|
| 778 |
|
---|
| 779 | /* Produce decimal digits from the scaled number. */
|
---|
[1b20da0] | 780 | int len = gen_fixed_dec_digits(w_scaled, scale, signif_d_cnt, frac_d_cnt,
|
---|
[3bacee1] | 781 | buf, buf_size, dec_exponent);
|
---|
[34b9299] | 782 |
|
---|
| 783 | assert(len <= MAX_DOUBLE_STR_LEN);
|
---|
| 784 | return len;
|
---|
| 785 | }
|
---|