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