Number.Dragon4.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Diagnostics;
  5. using System.Numerics;
  6. using Internal.Runtime.CompilerServices;
  7. namespace System
  8. {
  9. // This is a port of the `Dragon4` implementation here: http://www.ryanjuckett.com/programming/printing-floating-point-numbers/part-2/
  10. // The backing algorithm and the proofs behind it are described in more detail here: https://www.cs.indiana.edu/~dyb/pubs/FP-Printing-PLDI96.pdf
  11. internal static partial class Number
  12. {
  13. public static void Dragon4Double(double value, int cutoffNumber, bool isSignificantDigits, ref NumberBuffer number)
  14. {
  15. double v = double.IsNegative(value) ? -value : value;
  16. Debug.Assert(v > 0);
  17. Debug.Assert(double.IsFinite(v));
  18. ulong mantissa = ExtractFractionAndBiasedExponent(value, out int exponent);
  19. uint mantissaHighBitIdx = 0;
  20. bool hasUnequalMargins = false;
  21. if ((mantissa >> DiyFp.DoubleImplicitBitIndex) != 0)
  22. {
  23. mantissaHighBitIdx = DiyFp.DoubleImplicitBitIndex;
  24. hasUnequalMargins = (mantissa == (1UL << DiyFp.DoubleImplicitBitIndex));
  25. }
  26. else
  27. {
  28. Debug.Assert(mantissa != 0);
  29. mantissaHighBitIdx = (uint)BitOperations.Log2(mantissa);
  30. }
  31. int length = (int)(Dragon4(mantissa, exponent, mantissaHighBitIdx, hasUnequalMargins, cutoffNumber, isSignificantDigits, number.Digits, out int decimalExponent));
  32. number.Scale = decimalExponent + 1;
  33. number.Digits[length] = (byte)('\0');
  34. number.DigitsCount = length;
  35. }
  36. public static unsafe void Dragon4Single(float value, int cutoffNumber, bool isSignificantDigits, ref NumberBuffer number)
  37. {
  38. float v = float.IsNegative(value) ? -value : value;
  39. Debug.Assert(v > 0);
  40. Debug.Assert(float.IsFinite(v));
  41. uint mantissa = ExtractFractionAndBiasedExponent(value, out int exponent);
  42. uint mantissaHighBitIdx = 0;
  43. bool hasUnequalMargins = false;
  44. if ((mantissa >> DiyFp.SingleImplicitBitIndex) != 0)
  45. {
  46. mantissaHighBitIdx = DiyFp.SingleImplicitBitIndex;
  47. hasUnequalMargins = (mantissa == (1U << DiyFp.SingleImplicitBitIndex));
  48. }
  49. else
  50. {
  51. Debug.Assert(mantissa != 0);
  52. mantissaHighBitIdx = (uint)BitOperations.Log2(mantissa);
  53. }
  54. int length = (int)(Dragon4(mantissa, exponent, mantissaHighBitIdx, hasUnequalMargins, cutoffNumber, isSignificantDigits, number.Digits, out int decimalExponent));
  55. number.Scale = decimalExponent + 1;
  56. number.Digits[length] = (byte)('\0');
  57. number.DigitsCount = length;
  58. }
  59. // This is an implementation of the Dragon4 algorithm to convert a binary number in floating-point format to a decimal number in string format.
  60. // The function returns the number of digits written to the output buffer and the output is not NUL terminated.
  61. //
  62. // The floating point input value is (mantissa * 2^exponent).
  63. //
  64. // See the following papers for more information on the algorithm:
  65. // "How to Print Floating-Point Numbers Accurately"
  66. // Steele and White
  67. // http://kurtstephens.com/files/p372-steele.pdf
  68. // "Printing Floating-Point Numbers Quickly and Accurately"
  69. // Burger and Dybvig
  70. // http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.72.4656&rep=rep1&type=pdf
  71. private static unsafe uint Dragon4(ulong mantissa, int exponent, uint mantissaHighBitIdx, bool hasUnequalMargins, int cutoffNumber, bool isSignificantDigits, Span<byte> buffer, out int decimalExponent)
  72. {
  73. int curDigit = 0;
  74. Debug.Assert(buffer.Length > 0);
  75. // We deviate from the original algorithm and just assert that the mantissa
  76. // is not zero. Comparing to zero is fine since the caller should have set
  77. // the implicit bit of the mantissa, meaning it would only ever be zero if
  78. // the extracted exponent was also zero. And the assertion is fine since we
  79. // require that the DoubleToNumber handle zero itself.
  80. Debug.Assert(mantissa != 0);
  81. // Compute the initial state in integral form such that
  82. // value = scaledValue / scale
  83. // marginLow = scaledMarginLow / scale
  84. BigInteger scale; // positive scale applied to value and margin such that they can be represented as whole numbers
  85. BigInteger scaledValue; // scale * mantissa
  86. BigInteger scaledMarginLow; // scale * 0.5 * (distance between this floating-point number and its immediate lower value)
  87. // For normalized IEEE floating-point values, each time the exponent is incremented the margin also doubles.
  88. // That creates a subset of transition numbers where the high margin is twice the size of the low margin.
  89. BigInteger* pScaledMarginHigh;
  90. BigInteger optionalMarginHigh;
  91. if (hasUnequalMargins)
  92. {
  93. if (exponent > 0) // We have no fractional component
  94. {
  95. // 1) Expand the input value by multiplying out the mantissa and exponent.
  96. // This represents the input value in its whole number representation.
  97. // 2) Apply an additional scale of 2 such that later comparisons against the margin values are simplified.
  98. // 3) Set the margin value to the loweset mantissa bit's scale.
  99. // scaledValue = 2 * 2 * mantissa * 2^exponent
  100. scaledValue = new BigInteger(4 * mantissa);
  101. scaledValue.ShiftLeft((uint)(exponent));
  102. // scale = 2 * 2 * 1
  103. scale = new BigInteger(4);
  104. // scaledMarginLow = 2 * 2^(exponent - 1)
  105. BigInteger.Pow2((uint)(exponent), out scaledMarginLow);
  106. // scaledMarginHigh = 2 * 2 * 2^(exponent + 1)
  107. BigInteger.Pow2((uint)(exponent + 1), out optionalMarginHigh);
  108. }
  109. else // We have a fractional exponent
  110. {
  111. // In order to track the mantissa data as an integer, we store it as is with a large scale
  112. // scaledValue = 2 * 2 * mantissa
  113. scaledValue = new BigInteger(4 * mantissa);
  114. // scale = 2 * 2 * 2^(-exponent)
  115. BigInteger.Pow2((uint)(-exponent + 2), out scale);
  116. // scaledMarginLow = 2 * 2^(-1)
  117. scaledMarginLow = new BigInteger(1);
  118. // scaledMarginHigh = 2 * 2 * 2^(-1)
  119. optionalMarginHigh = new BigInteger(2);
  120. }
  121. // The high and low margins are different
  122. pScaledMarginHigh = &optionalMarginHigh;
  123. }
  124. else
  125. {
  126. if (exponent > 0) // We have no fractional component
  127. {
  128. // 1) Expand the input value by multiplying out the mantissa and exponent.
  129. // This represents the input value in its whole number representation.
  130. // 2) Apply an additional scale of 2 such that later comparisons against the margin values are simplified.
  131. // 3) Set the margin value to the lowest mantissa bit's scale.
  132. // scaledValue = 2 * mantissa*2^exponent
  133. scaledValue = new BigInteger(2 * mantissa);
  134. scaledValue.ShiftLeft((uint)(exponent));
  135. // scale = 2 * 1
  136. scale = new BigInteger(2);
  137. // scaledMarginLow = 2 * 2^(exponent-1)
  138. BigInteger.Pow2((uint)(exponent), out scaledMarginLow);
  139. }
  140. else // We have a fractional exponent
  141. {
  142. // In order to track the mantissa data as an integer, we store it as is with a large scale
  143. // scaledValue = 2 * mantissa
  144. scaledValue = new BigInteger(2 * mantissa);
  145. // scale = 2 * 2^(-exponent)
  146. BigInteger.Pow2((uint)(-exponent + 1), out scale);
  147. // scaledMarginLow = 2 * 2^(-1)
  148. scaledMarginLow = new BigInteger(1);
  149. }
  150. // The high and low margins are equal
  151. pScaledMarginHigh = &scaledMarginLow;
  152. }
  153. // Compute an estimate for digitExponent that will be correct or undershoot by one.
  154. //
  155. // This optimization is based on the paper "Printing Floating-Point Numbers Quickly and Accurately" by Burger and Dybvig http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.72.4656&rep=rep1&type=pdf
  156. //
  157. // We perform an additional subtraction of 0.69 to increase the frequency of a failed estimate because that lets us take a faster branch in the code.
  158. // 0.69 is chosen because 0.69 + log10(2) is less than one by a reasonable epsilon that will account for any floating point error.
  159. //
  160. // We want to set digitExponent to floor(log10(v)) + 1
  161. // v = mantissa * 2^exponent
  162. // log2(v) = log2(mantissa) + exponent;
  163. // log10(v) = log2(v) * log10(2)
  164. // floor(log2(v)) = mantissaHighBitIdx + exponent;
  165. // log10(v) - log10(2) < (mantissaHighBitIdx + exponent) * log10(2) <= log10(v)
  166. // log10(v) < (mantissaHighBitIdx + exponent) * log10(2) + log10(2) <= log10(v) + log10(2)
  167. // floor(log10(v)) < ceil((mantissaHighBitIdx + exponent) * log10(2)) <= floor(log10(v)) + 1
  168. const double Log10V2 = 0.30102999566398119521373889472449;
  169. int digitExponent = (int)(Math.Ceiling(((int)(mantissaHighBitIdx) + exponent) * Log10V2 - 0.69));
  170. // Divide value by 10^digitExponent.
  171. if (digitExponent > 0)
  172. {
  173. // The exponent is positive creating a division so we multiply up the scale.
  174. scale.MultiplyPow10((uint)(digitExponent));
  175. }
  176. else if (digitExponent < 0)
  177. {
  178. // The exponent is negative creating a multiplication so we multiply up the scaledValue, scaledMarginLow and scaledMarginHigh.
  179. BigInteger.Pow10((uint)(-digitExponent), out BigInteger pow10);
  180. scaledValue.Multiply(ref pow10);
  181. scaledMarginLow.Multiply(ref pow10);
  182. if (pScaledMarginHigh != &scaledMarginLow)
  183. {
  184. BigInteger.Multiply(ref scaledMarginLow, 2, ref *pScaledMarginHigh);
  185. }
  186. }
  187. // If (value >= 1), our estimate for digitExponent was too low
  188. if (BigInteger.Compare(ref scaledValue, ref scale) >= 0)
  189. {
  190. // The exponent estimate was incorrect.
  191. // Increment the exponent and don't perform the premultiply needed for the first loop iteration.
  192. digitExponent = digitExponent + 1;
  193. }
  194. else
  195. {
  196. // The exponent estimate was correct.
  197. // Multiply larger by the output base to prepare for the first loop iteration.
  198. scaledValue.Multiply10();
  199. scaledMarginLow.Multiply10();
  200. if (pScaledMarginHigh != &scaledMarginLow)
  201. {
  202. BigInteger.Multiply(ref scaledMarginLow, 2, ref *pScaledMarginHigh);
  203. }
  204. }
  205. // Compute the cutoff exponent (the exponent of the final digit to print).
  206. // Default to the maximum size of the output buffer.
  207. int cutoffExponent = digitExponent - buffer.Length;
  208. if (cutoffNumber != -1)
  209. {
  210. int desiredCutoffExponent = 0;
  211. if (isSignificantDigits)
  212. {
  213. // We asked for a specific number of significant digits.
  214. Debug.Assert(cutoffNumber > 0);
  215. desiredCutoffExponent = digitExponent - cutoffNumber;
  216. }
  217. else
  218. {
  219. // We asked for a specific number of fractional digits.
  220. Debug.Assert(cutoffNumber >= 0);
  221. desiredCutoffExponent = -cutoffNumber;
  222. }
  223. if (desiredCutoffExponent > cutoffExponent)
  224. {
  225. // Only select the new cutoffExponent if it won't overflow the destination buffer.
  226. cutoffExponent = desiredCutoffExponent;
  227. }
  228. }
  229. // Output the exponent of the first digit we will print
  230. decimalExponent = --digitExponent;
  231. // In preparation for calling BigInteger.HeuristicDivie(), we need to scale up our values such that the highest block of the denominator is greater than or equal to 8.
  232. // We also need to guarantee that the numerator can never have a length greater than the denominator after each loop iteration.
  233. // This requires the highest block of the denominator to be less than or equal to 429496729 which is the highest number that can be multiplied by 10 without overflowing to a new block.
  234. Debug.Assert(scale.GetLength() > 0);
  235. uint hiBlock = scale.GetBlock((uint)(scale.GetLength() - 1));
  236. if ((hiBlock < 8) || (hiBlock > 429496729))
  237. {
  238. // Perform a bit shift on all values to get the highest block of the denominator into the range [8,429496729].
  239. // We are more likely to make accurate quotient estimations in BigInteger.HeuristicDivide() with higher denominator values so we shift the denominator to place the highest bit at index 27 of the highest block.
  240. // This is safe because (2^28 - 1) = 268435455 which is less than 429496729.
  241. // This means that all values with a highest bit at index 27 are within range.
  242. Debug.Assert(hiBlock != 0);
  243. uint hiBlockLog2 = (uint)BitOperations.Log2(hiBlock);
  244. Debug.Assert((hiBlockLog2 < 3) || (hiBlockLog2 > 27));
  245. uint shift = (32 + 27 - hiBlockLog2) % 32;
  246. scale.ShiftLeft(shift);
  247. scaledValue.ShiftLeft(shift);
  248. scaledMarginLow.ShiftLeft(shift);
  249. if (pScaledMarginHigh != &scaledMarginLow)
  250. {
  251. BigInteger.Multiply(ref scaledMarginLow, 2, ref *pScaledMarginHigh);
  252. }
  253. }
  254. // These values are used to inspect why the print loop terminated so we can properly round the final digit.
  255. bool low; // did the value get within marginLow distance from zero
  256. bool high; // did the value get within marginHigh distance from one
  257. uint outputDigit; // current digit being output
  258. if (cutoffNumber == -1)
  259. {
  260. Debug.Assert(isSignificantDigits);
  261. Debug.Assert(digitExponent >= cutoffExponent);
  262. // For the unique cutoff mode, we will try to print until we have reached a level of precision that uniquely distinguishes this value from its neighbors.
  263. // If we run out of space in the output buffer, we terminate early.
  264. while (true)
  265. {
  266. // divide out the scale to extract the digit
  267. outputDigit = BigInteger.HeuristicDivide(ref scaledValue, ref scale);
  268. Debug.Assert(outputDigit < 10);
  269. // update the high end of the value
  270. BigInteger.Add(ref scaledValue, ref *pScaledMarginHigh, out BigInteger scaledValueHigh);
  271. // stop looping if we are far enough away from our neighboring values or if we have reached the cutoff digit
  272. low = BigInteger.Compare(ref scaledValue, ref scaledMarginLow) < 0;
  273. high = BigInteger.Compare(ref scaledValueHigh, ref scale) > 0;
  274. if (low || high || (digitExponent == cutoffExponent))
  275. {
  276. break;
  277. }
  278. // store the output digit
  279. buffer[curDigit] = (byte)('0' + outputDigit);
  280. curDigit += 1;
  281. // multiply larger by the output base
  282. scaledValue.Multiply10();
  283. scaledMarginLow.Multiply10();
  284. if (pScaledMarginHigh != &scaledMarginLow)
  285. {
  286. BigInteger.Multiply(ref scaledMarginLow, 2, ref *pScaledMarginHigh);
  287. }
  288. digitExponent--;
  289. }
  290. }
  291. else if (digitExponent >= cutoffExponent)
  292. {
  293. Debug.Assert((cutoffNumber > 0) || ((cutoffNumber == 0) && !isSignificantDigits));
  294. // For length based cutoff modes, we will try to print until we have exhausted all precision (i.e. all remaining digits are zeros) or until we reach the desired cutoff digit.
  295. low = false;
  296. high = false;
  297. while (true)
  298. {
  299. // divide out the scale to extract the digit
  300. outputDigit = BigInteger.HeuristicDivide(ref scaledValue, ref scale);
  301. Debug.Assert(outputDigit < 10);
  302. if (scaledValue.IsZero() || (digitExponent <= cutoffExponent))
  303. {
  304. break;
  305. }
  306. // store the output digit
  307. buffer[curDigit] = (byte)('0' + outputDigit);
  308. curDigit += 1;
  309. // multiply larger by the output base
  310. scaledValue.Multiply10();
  311. digitExponent--;
  312. }
  313. }
  314. else
  315. {
  316. // In the scenario where the first significant digit is after the cutoff, we want to treat that
  317. // first significant digit as the rounding digit. If the first significant would cause the next
  318. // digit to round, we will increase the decimalExponent by one and set the previous digit to one.
  319. // This ensures we correctly handle the case where the first significant digit is exactly one after
  320. // the cutoff, it is a 4, and the subsequent digit would round that to 5 inducing a double rounding
  321. // bug when NumberToString does its own rounding checks. However, if the first significant digit
  322. // would not cause the next one to round, we preserve that digit as is.
  323. // divide out the scale to extract the digit
  324. outputDigit = BigInteger.HeuristicDivide(ref scaledValue, ref scale);
  325. Debug.Assert((0 < outputDigit) && (outputDigit < 10));
  326. if ((outputDigit > 5) || ((outputDigit == 5) && !scaledValue.IsZero()))
  327. {
  328. decimalExponent++;
  329. outputDigit = 1;
  330. }
  331. buffer[curDigit] = (byte)('0' + outputDigit);
  332. curDigit += 1;
  333. // return the number of digits output
  334. return (uint)(curDigit);
  335. }
  336. // round off the final digit
  337. // default to rounding down if value got too close to 0
  338. bool roundDown = low;
  339. if (low == high) // is it legal to round up and down
  340. {
  341. // round to the closest digit by comparing value with 0.5.
  342. //
  343. // To do this we need to convert the inequality to large integer values.
  344. // compare(value, 0.5)
  345. // compare(scale * value, scale * 0.5)
  346. // compare(2 * scale * value, scale)
  347. scaledValue.Multiply(2);
  348. int compare = BigInteger.Compare(ref scaledValue, ref scale);
  349. roundDown = compare < 0;
  350. // if we are directly in the middle, round towards the even digit (i.e. IEEE rouding rules)
  351. if (compare == 0)
  352. {
  353. roundDown = (outputDigit & 1) == 0;
  354. }
  355. }
  356. // print the rounded digit
  357. if (roundDown)
  358. {
  359. buffer[curDigit] = (byte)('0' + outputDigit);
  360. curDigit += 1;
  361. }
  362. else if (outputDigit == 9) // handle rounding up
  363. {
  364. // find the first non-nine prior digit
  365. while (true)
  366. {
  367. // if we are at the first digit
  368. if (curDigit == 0)
  369. {
  370. // output 1 at the next highest exponent
  371. buffer[curDigit] = (byte)('1');
  372. curDigit += 1;
  373. decimalExponent += 1;
  374. break;
  375. }
  376. curDigit -= 1;
  377. if (buffer[curDigit] != '9')
  378. {
  379. // increment the digit
  380. buffer[curDigit] += 1;
  381. curDigit += 1;
  382. break;
  383. }
  384. }
  385. }
  386. else
  387. {
  388. // values in the range [0,8] can perform a simple round up
  389. buffer[curDigit] = (byte)('0' + outputDigit + 1);
  390. curDigit += 1;
  391. }
  392. // return the number of digits output
  393. uint outputLen = (uint)(curDigit);
  394. Debug.Assert(outputLen <= buffer.Length);
  395. return outputLen;
  396. }
  397. }
  398. }