| 13470 | */ |
| 13471 | JSON_HEDLEY_NON_NULL(1) |
| 13472 | inline void grisu2(char* buf, int& len, int& decimal_exponent, |
| 13473 | diyfp m_minus, diyfp v, diyfp m_plus) |
| 13474 | { |
| 13475 | assert(m_plus.e == m_minus.e); |
| 13476 | assert(m_plus.e == v.e); |
| 13477 | |
| 13478 | // --------(-----------------------+-----------------------)-------- (A) |
| 13479 | // m- v m+ |
| 13480 | // |
| 13481 | // --------------------(-----------+-----------------------)-------- (B) |
| 13482 | // m- v m+ |
| 13483 | // |
| 13484 | // First scale v (and m- and m+) such that the exponent is in the range |
| 13485 | // [alpha, gamma]. |
| 13486 | |
| 13487 | const cached_power cached = get_cached_power_for_binary_exponent(m_plus.e); |
| 13488 | |
| 13489 | const diyfp c_minus_k(cached.f, cached.e); // = c ~= 10^-k |
| 13490 | |
| 13491 | // The exponent of the products is = v.e + c_minus_k.e + q and is in the range [alpha,gamma] |
| 13492 | const diyfp w = diyfp::mul(v, c_minus_k); |
| 13493 | const diyfp w_minus = diyfp::mul(m_minus, c_minus_k); |
| 13494 | const diyfp w_plus = diyfp::mul(m_plus, c_minus_k); |
| 13495 | |
| 13496 | // ----(---+---)---------------(---+---)---------------(---+---)---- |
| 13497 | // w- w w+ |
| 13498 | // = c*m- = c*v = c*m+ |
| 13499 | // |
| 13500 | // diyfp::mul rounds its result and c_minus_k is approximated too. w, w- and |
| 13501 | // w+ are now off by a small amount. |
| 13502 | // In fact: |
| 13503 | // |
| 13504 | // w - v * 10^k < 1 ulp |
| 13505 | // |
| 13506 | // To account for this inaccuracy, add resp. subtract 1 ulp. |
| 13507 | // |
| 13508 | // --------+---[---------------(---+---)---------------]---+-------- |
| 13509 | // w- M- w M+ w+ |
| 13510 | // |
| 13511 | // Now any number in [M-, M+] (bounds included) will round to w when input, |
| 13512 | // regardless of how the input rounding algorithm breaks ties. |
| 13513 | // |
| 13514 | // And digit_gen generates the shortest possible such number in [M-, M+]. |
| 13515 | // Note that this does not mean that Grisu2 always generates the shortest |
| 13516 | // possible number in the interval (m-, m+). |
| 13517 | const diyfp M_minus(w_minus.f + 1, w_minus.e); |
| 13518 | const diyfp M_plus (w_plus.f - 1, w_plus.e ); |
| 13519 | |
| 13520 | decimal_exponent = -cached.k; // = -(-k) = k |
| 13521 | |
| 13522 | grisu2_digit_gen(buf, len, decimal_exponent, M_minus, w, M_plus); |
| 13523 | } |
| 13524 | |
| 13525 | /*! |
| 13526 | v = buf * 10^decimal_exponent |
no test coverage detected