formatfloat.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. /*
  2. * This file is part of the MicroPython project, http://micropython.org/
  3. *
  4. * The MIT License (MIT)
  5. *
  6. * Copyright (c) 2013, 2014 Damien P. George
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy
  9. * of this software and associated documentation files (the "Software"), to deal
  10. * in the Software without restriction, including without limitation the rights
  11. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. * copies of the Software, and to permit persons to whom the Software is
  13. * furnished to do so, subject to the following conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in
  16. * all copies or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  24. * THE SOFTWARE.
  25. */
  26. #include "py/mpconfig.h"
  27. #include "py/misc.h"
  28. #if MICROPY_FLOAT_IMPL != MICROPY_FLOAT_IMPL_NONE
  29. #include <assert.h>
  30. #include <stdlib.h>
  31. #include <stdint.h>
  32. #include <math.h>
  33. #include "py/formatfloat.h"
  34. /***********************************************************************
  35. Routine for converting a arbitrary floating
  36. point number into a string.
  37. The code in this function was inspired from Fred Bayer's pdouble.c.
  38. Since pdouble.c was released as Public Domain, I'm releasing this
  39. code as public domain as well.
  40. The original code can be found in https://github.com/dhylands/format-float
  41. Dave Hylands
  42. ***********************************************************************/
  43. #if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT
  44. // 1 sign bit, 8 exponent bits, and 23 mantissa bits.
  45. // exponent values 0 and 255 are reserved, exponent can be 1 to 254.
  46. // exponent is stored with a bias of 127.
  47. // The min and max floats are on the order of 1x10^37 and 1x10^-37
  48. #define FPTYPE float
  49. #define FPCONST(x) x##F
  50. #define FPROUND_TO_ONE 0.9999995F
  51. #define FPDECEXP 32
  52. #define FPMIN_BUF_SIZE 6 // +9e+99
  53. #define FLT_SIGN_MASK 0x80000000
  54. static inline int fp_signbit(float x) {
  55. mp_float_union_t fb = {x};
  56. return fb.i & FLT_SIGN_MASK;
  57. }
  58. #define fp_isnan(x) isnan(x)
  59. #define fp_isinf(x) isinf(x)
  60. static inline int fp_iszero(float x) {
  61. mp_float_union_t fb = {x};
  62. return fb.i == 0;
  63. }
  64. static inline int fp_isless1(float x) {
  65. mp_float_union_t fb = {x};
  66. return fb.i < 0x3f800000;
  67. }
  68. #elif MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE
  69. #define FPTYPE double
  70. #define FPCONST(x) x
  71. #define FPROUND_TO_ONE 0.999999999995
  72. #define FPDECEXP 256
  73. #define FPMIN_BUF_SIZE 7 // +9e+199
  74. #define fp_signbit(x) signbit(x)
  75. #define fp_isnan(x) isnan(x)
  76. #define fp_isinf(x) isinf(x)
  77. #define fp_iszero(x) (x == 0)
  78. #define fp_isless1(x) (x < 1.0)
  79. #endif // MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT/DOUBLE
  80. static inline int fp_expval(FPTYPE x) {
  81. mp_float_union_t fb = {x};
  82. return (int)((fb.i >> MP_FLOAT_FRAC_BITS) & (~(0xFFFFFFFF << MP_FLOAT_EXP_BITS))) - MP_FLOAT_EXP_OFFSET;
  83. }
  84. int mp_format_float(FPTYPE f, char *buf, size_t buf_size, char fmt, int prec, char sign) {
  85. char *s = buf;
  86. if (buf_size <= FPMIN_BUF_SIZE) {
  87. // FPMIN_BUF_SIZE is the minimum size needed to store any FP number.
  88. // If the buffer does not have enough room for this (plus null terminator)
  89. // then don't try to format the float.
  90. if (buf_size >= 2) {
  91. *s++ = '?';
  92. }
  93. if (buf_size >= 1) {
  94. *s = '\0';
  95. }
  96. return buf_size >= 2;
  97. }
  98. if (fp_signbit(f) && !fp_isnan(f)) {
  99. *s++ = '-';
  100. f = -f;
  101. } else {
  102. if (sign) {
  103. *s++ = sign;
  104. }
  105. }
  106. // buf_remaining contains bytes available for digits and exponent.
  107. // It is buf_size minus room for the sign and null byte.
  108. int buf_remaining = buf_size - 1 - (s - buf);
  109. {
  110. char uc = fmt & 0x20;
  111. if (fp_isinf(f)) {
  112. *s++ = 'I' ^ uc;
  113. *s++ = 'N' ^ uc;
  114. *s++ = 'F' ^ uc;
  115. goto ret;
  116. } else if (fp_isnan(f)) {
  117. *s++ = 'N' ^ uc;
  118. *s++ = 'A' ^ uc;
  119. *s++ = 'N' ^ uc;
  120. ret:
  121. *s = '\0';
  122. return s - buf;
  123. }
  124. }
  125. if (prec < 0) {
  126. prec = 6;
  127. }
  128. char e_char = 'E' | (fmt & 0x20); // e_char will match case of fmt
  129. fmt |= 0x20; // Force fmt to be lowercase
  130. char org_fmt = fmt;
  131. if (fmt == 'g' && prec == 0) {
  132. prec = 1;
  133. }
  134. int e;
  135. int dec = 0;
  136. char e_sign = '\0';
  137. int num_digits = 0;
  138. int signed_e = 0;
  139. // Approximate power of 10 exponent from binary exponent.
  140. // abs(e_guess) is lower bound on abs(power of 10 exponent).
  141. int e_guess = (int)(fp_expval(f) * FPCONST(0.3010299956639812)); // 1/log2(10).
  142. if (fp_iszero(f)) {
  143. e = 0;
  144. if (fmt == 'f') {
  145. // Truncate precision to prevent buffer overflow
  146. if (prec + 2 > buf_remaining) {
  147. prec = buf_remaining - 2;
  148. }
  149. num_digits = prec + 1;
  150. } else {
  151. // Truncate precision to prevent buffer overflow
  152. if (prec + 6 > buf_remaining) {
  153. prec = buf_remaining - 6;
  154. }
  155. if (fmt == 'e') {
  156. e_sign = '+';
  157. }
  158. }
  159. } else if (fp_isless1(f)) {
  160. FPTYPE f_entry = f; // Save f in case we go to 'f' format.
  161. // Build negative exponent
  162. e = -e_guess;
  163. FPTYPE u_base = MICROPY_FLOAT_C_FUN(pow)(10, -e);
  164. while (u_base > f) {
  165. ++e;
  166. u_base = MICROPY_FLOAT_C_FUN(pow)(10, -e);
  167. }
  168. // Normalize out the inferred unit. Use divide because
  169. // pow(10, e) * pow(10, -e) is slightly < 1 for some e in float32
  170. // (e.g. print("%.12f" % ((1e13) * (1e-13))))
  171. f /= u_base;
  172. // If the user specified 'g' format, and e is <= 4, then we'll switch
  173. // to the fixed format ('f')
  174. if (fmt == 'f' || (fmt == 'g' && e <= 4)) {
  175. fmt = 'f';
  176. dec = 0;
  177. if (org_fmt == 'g') {
  178. prec += (e - 1);
  179. }
  180. // truncate precision to prevent buffer overflow
  181. if (prec + 2 > buf_remaining) {
  182. prec = buf_remaining - 2;
  183. }
  184. num_digits = prec;
  185. signed_e = 0;
  186. f = f_entry;
  187. ++num_digits;
  188. } else {
  189. // For e & g formats, we'll be printing the exponent, so set the
  190. // sign.
  191. e_sign = '-';
  192. dec = 0;
  193. if (prec > (buf_remaining - FPMIN_BUF_SIZE)) {
  194. prec = buf_remaining - FPMIN_BUF_SIZE;
  195. if (fmt == 'g') {
  196. prec++;
  197. }
  198. }
  199. signed_e = -e;
  200. }
  201. } else {
  202. // Build positive exponent.
  203. // We don't modify f at this point to avoid inaccuracies from
  204. // scaling it. Instead, we find the product of powers of 10
  205. // that is not greater than it, and use that to start the
  206. // mantissa.
  207. e = e_guess;
  208. FPTYPE next_u = MICROPY_FLOAT_C_FUN(pow)(10, e + 1);
  209. while (f >= next_u) {
  210. ++e;
  211. next_u = MICROPY_FLOAT_C_FUN(pow)(10, e + 1);
  212. }
  213. // If the user specified fixed format (fmt == 'f') and e makes the
  214. // number too big to fit into the available buffer, then we'll
  215. // switch to the 'e' format.
  216. if (fmt == 'f') {
  217. if (e >= buf_remaining) {
  218. fmt = 'e';
  219. } else if ((e + prec + 2) > buf_remaining) {
  220. prec = buf_remaining - e - 2;
  221. if (prec < 0) {
  222. // This means no decimal point, so we can add one back
  223. // for the decimal.
  224. prec++;
  225. }
  226. }
  227. }
  228. if (fmt == 'e' && prec > (buf_remaining - FPMIN_BUF_SIZE)) {
  229. prec = buf_remaining - FPMIN_BUF_SIZE;
  230. }
  231. if (fmt == 'g') {
  232. // Truncate precision to prevent buffer overflow
  233. if (prec + (FPMIN_BUF_SIZE - 1) > buf_remaining) {
  234. prec = buf_remaining - (FPMIN_BUF_SIZE - 1);
  235. }
  236. }
  237. // If the user specified 'g' format, and e is < prec, then we'll switch
  238. // to the fixed format.
  239. if (fmt == 'g' && e < prec) {
  240. fmt = 'f';
  241. prec -= (e + 1);
  242. }
  243. if (fmt == 'f') {
  244. dec = e;
  245. num_digits = prec + e + 1;
  246. } else {
  247. e_sign = '+';
  248. }
  249. signed_e = e;
  250. }
  251. if (prec < 0) {
  252. // This can happen when the prec is trimmed to prevent buffer overflow
  253. prec = 0;
  254. }
  255. // At this point e contains the absolute value of the power of 10 exponent.
  256. // (dec + 1) == the number of dgits before the decimal.
  257. // For e, prec is # digits after the decimal
  258. // For f, prec is # digits after the decimal
  259. // For g, prec is the max number of significant digits
  260. //
  261. // For e & g there will be a single digit before the decimal
  262. // for f there will be e digits before the decimal
  263. if (fmt == 'e') {
  264. num_digits = prec + 1;
  265. } else if (fmt == 'g') {
  266. if (prec == 0) {
  267. prec = 1;
  268. }
  269. num_digits = prec;
  270. }
  271. int d = 0;
  272. for (int digit_index = signed_e; num_digits >= 0; --digit_index) {
  273. FPTYPE u_base = FPCONST(1.0);
  274. if (digit_index > 0) {
  275. // Generate 10^digit_index for positive digit_index.
  276. u_base = MICROPY_FLOAT_C_FUN(pow)(10, digit_index);
  277. }
  278. for (d = 0; d < 9; ++d) {
  279. if (f < u_base) {
  280. break;
  281. }
  282. f -= u_base;
  283. }
  284. // We calculate one more digit than we display, to use in rounding
  285. // below. So only emit the digit if it's one that we display.
  286. if (num_digits > 0) {
  287. // Emit this number (the leading digit).
  288. *s++ = '0' + d;
  289. if (dec == 0 && prec > 0) {
  290. *s++ = '.';
  291. }
  292. }
  293. --dec;
  294. --num_digits;
  295. if (digit_index <= 0) {
  296. // Once we get below 1.0, we scale up f instead of calculating
  297. // negative powers of 10 in u_base. This provides better
  298. // renditions of exact decimals like 1/16 etc.
  299. f *= FPCONST(10.0);
  300. }
  301. }
  302. // Rounding. If the next digit to print is >= 5, round up.
  303. if (d >= 5) {
  304. char *rs = s;
  305. rs--;
  306. while (1) {
  307. if (*rs == '.') {
  308. rs--;
  309. continue;
  310. }
  311. if (*rs < '0' || *rs > '9') {
  312. // + or -
  313. rs++; // So we sit on the digit to the right of the sign
  314. break;
  315. }
  316. if (*rs < '9') {
  317. (*rs)++;
  318. break;
  319. }
  320. *rs = '0';
  321. if (rs == buf) {
  322. break;
  323. }
  324. rs--;
  325. }
  326. if (*rs == '0') {
  327. // We need to insert a 1
  328. if (rs[1] == '.' && fmt != 'f') {
  329. // We're going to round 9.99 to 10.00
  330. // Move the decimal point
  331. rs[0] = '.';
  332. rs[1] = '0';
  333. if (e_sign == '-') {
  334. e--;
  335. if (e == 0) {
  336. e_sign = '+';
  337. }
  338. } else {
  339. e++;
  340. }
  341. } else {
  342. // Need at extra digit at the end to make room for the leading '1'
  343. // but if we're at the buffer size limit, just drop the final digit.
  344. if ((size_t)(s + 1 - buf) < buf_size) {
  345. s++;
  346. }
  347. }
  348. char *ss = s;
  349. while (ss > rs) {
  350. *ss = ss[-1];
  351. ss--;
  352. }
  353. *rs = '1';
  354. }
  355. }
  356. // verify that we did not overrun the input buffer so far
  357. assert((size_t)(s + 1 - buf) <= buf_size);
  358. if (org_fmt == 'g' && prec > 0) {
  359. // Remove trailing zeros and a trailing decimal point
  360. while (s[-1] == '0') {
  361. s--;
  362. }
  363. if (s[-1] == '.') {
  364. s--;
  365. }
  366. }
  367. // Append the exponent
  368. if (e_sign) {
  369. *s++ = e_char;
  370. *s++ = e_sign;
  371. if (FPMIN_BUF_SIZE == 7 && e >= 100) {
  372. *s++ = '0' + (e / 100);
  373. }
  374. *s++ = '0' + ((e / 10) % 10);
  375. *s++ = '0' + (e % 10);
  376. }
  377. *s = '\0';
  378. // verify that we did not overrun the input buffer
  379. assert((size_t)(s + 1 - buf) <= buf_size);
  380. return s - buf;
  381. }
  382. #endif // MICROPY_FLOAT_IMPL != MICROPY_FLOAT_IMPL_NONE