formatfloat.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  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. #if MICROPY_FLOAT_IMPL != MICROPY_FLOAT_IMPL_NONE
  28. #include <assert.h>
  29. #include <stdlib.h>
  30. #include <stdint.h>
  31. #include <math.h>
  32. #include "py/formatfloat.h"
  33. /***********************************************************************
  34. Routine for converting a arbitrary floating
  35. point number into a string.
  36. The code in this funcion was inspired from Fred Bayer's pdouble.c.
  37. Since pdouble.c was released as Public Domain, I'm releasing this
  38. code as public domain as well.
  39. The original code can be found in https://github.com/dhylands/format-float
  40. Dave Hylands
  41. ***********************************************************************/
  42. #if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT
  43. // 1 sign bit, 8 exponent bits, and 23 mantissa bits.
  44. // exponent values 0 and 255 are reserved, exponent can be 1 to 254.
  45. // exponent is stored with a bias of 127.
  46. // The min and max floats are on the order of 1x10^37 and 1x10^-37
  47. #define FPTYPE float
  48. #define FPCONST(x) x##F
  49. #define FPROUND_TO_ONE 0.9999995F
  50. #define FPDECEXP 32
  51. #define FPMIN_BUF_SIZE 6 // +9e+99
  52. #define FLT_SIGN_MASK 0x80000000
  53. #define FLT_EXP_MASK 0x7F800000
  54. #define FLT_MAN_MASK 0x007FFFFF
  55. union floatbits {
  56. float f;
  57. uint32_t u;
  58. };
  59. static inline int fp_signbit(float x) {
  60. union floatbits fb = {x};
  61. return fb.u & FLT_SIGN_MASK;
  62. }
  63. #define fp_isnan(x) isnan(x)
  64. #define fp_isinf(x) isinf(x)
  65. static inline int fp_iszero(float x) {
  66. union floatbits fb = {x};
  67. return fb.u == 0;
  68. }
  69. static inline int fp_isless1(float x) {
  70. union floatbits fb = {x};
  71. return fb.u < 0x3f800000;
  72. }
  73. #elif MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE
  74. #define FPTYPE double
  75. #define FPCONST(x) x
  76. #define FPROUND_TO_ONE 0.999999999995
  77. #define FPDECEXP 256
  78. #define FPMIN_BUF_SIZE 7 // +9e+199
  79. #define fp_signbit(x) signbit(x)
  80. #define fp_isnan(x) isnan(x)
  81. #define fp_isinf(x) isinf(x)
  82. #define fp_iszero(x) (x == 0)
  83. #define fp_isless1(x) (x < 1.0)
  84. #endif
  85. static const FPTYPE g_pos_pow[] = {
  86. #if FPDECEXP > 32
  87. MICROPY_FLOAT_CONST(1e256), MICROPY_FLOAT_CONST(1e128), MICROPY_FLOAT_CONST(1e64),
  88. #endif
  89. MICROPY_FLOAT_CONST(1e32), MICROPY_FLOAT_CONST(1e16), MICROPY_FLOAT_CONST(1e8), MICROPY_FLOAT_CONST(1e4), MICROPY_FLOAT_CONST(1e2), MICROPY_FLOAT_CONST(1e1)
  90. };
  91. static const FPTYPE g_neg_pow[] = {
  92. #if FPDECEXP > 32
  93. MICROPY_FLOAT_CONST(1e-256), MICROPY_FLOAT_CONST(1e-128), MICROPY_FLOAT_CONST(1e-64),
  94. #endif
  95. MICROPY_FLOAT_CONST(1e-32), MICROPY_FLOAT_CONST(1e-16), MICROPY_FLOAT_CONST(1e-8), MICROPY_FLOAT_CONST(1e-4), MICROPY_FLOAT_CONST(1e-2), MICROPY_FLOAT_CONST(1e-1)
  96. };
  97. int mp_format_float(FPTYPE f, char *buf, size_t buf_size, char fmt, int prec, char sign) {
  98. char *s = buf;
  99. if (buf_size <= FPMIN_BUF_SIZE) {
  100. // FPMIN_BUF_SIZE is the minimum size needed to store any FP number.
  101. // If the buffer does not have enough room for this (plus null terminator)
  102. // then don't try to format the float.
  103. if (buf_size >= 2) {
  104. *s++ = '?';
  105. }
  106. if (buf_size >= 1) {
  107. *s = '\0';
  108. }
  109. return buf_size >= 2;
  110. }
  111. if (fp_signbit(f) && !fp_isnan(f)) {
  112. *s++ = '-';
  113. f = -f;
  114. } else {
  115. if (sign) {
  116. *s++ = sign;
  117. }
  118. }
  119. // buf_remaining contains bytes available for digits and exponent.
  120. // It is buf_size minus room for the sign and null byte.
  121. int buf_remaining = buf_size - 1 - (s - buf);
  122. {
  123. char uc = fmt & 0x20;
  124. if (fp_isinf(f)) {
  125. *s++ = 'I' ^ uc;
  126. *s++ = 'N' ^ uc;
  127. *s++ = 'F' ^ uc;
  128. goto ret;
  129. } else if (fp_isnan(f)) {
  130. *s++ = 'N' ^ uc;
  131. *s++ = 'A' ^ uc;
  132. *s++ = 'N' ^ uc;
  133. ret:
  134. *s = '\0';
  135. return s - buf;
  136. }
  137. }
  138. if (prec < 0) {
  139. prec = 6;
  140. }
  141. char e_char = 'E' | (fmt & 0x20); // e_char will match case of fmt
  142. fmt |= 0x20; // Force fmt to be lowercase
  143. char org_fmt = fmt;
  144. if (fmt == 'g' && prec == 0) {
  145. prec = 1;
  146. }
  147. int e, e1;
  148. int dec = 0;
  149. char e_sign = '\0';
  150. int num_digits = 0;
  151. const FPTYPE *pos_pow = g_pos_pow;
  152. const FPTYPE *neg_pow = g_neg_pow;
  153. if (fp_iszero(f)) {
  154. e = 0;
  155. if (fmt == 'f') {
  156. // Truncate precision to prevent buffer overflow
  157. if (prec + 2 > buf_remaining) {
  158. prec = buf_remaining - 2;
  159. }
  160. num_digits = prec + 1;
  161. } else {
  162. // Truncate precision to prevent buffer overflow
  163. if (prec + 6 > buf_remaining) {
  164. prec = buf_remaining - 6;
  165. }
  166. if (fmt == 'e') {
  167. e_sign = '+';
  168. }
  169. }
  170. } else if (fp_isless1(f)) {
  171. // We need to figure out what an integer digit will be used
  172. // in case 'f' is used (or we revert other format to it below).
  173. // As we just tested number to be <1, this is obviously 0,
  174. // but we can round it up to 1 below.
  175. char first_dig = '0';
  176. if (f >= FPROUND_TO_ONE) {
  177. first_dig = '1';
  178. }
  179. // Build negative exponent
  180. for (e = 0, e1 = FPDECEXP; e1; e1 >>= 1, pos_pow++, neg_pow++) {
  181. if (*neg_pow > f) {
  182. e += e1;
  183. f *= *pos_pow;
  184. }
  185. }
  186. char e_sign_char = '-';
  187. if (fp_isless1(f) && f >= FPROUND_TO_ONE) {
  188. f = FPCONST(1.0);
  189. if (e == 0) {
  190. e_sign_char = '+';
  191. }
  192. } else if (fp_isless1(f)) {
  193. e++;
  194. f *= FPCONST(10.0);
  195. }
  196. // If the user specified 'g' format, and e is <= 4, then we'll switch
  197. // to the fixed format ('f')
  198. if (fmt == 'f' || (fmt == 'g' && e <= 4)) {
  199. fmt = 'f';
  200. dec = -1;
  201. *s++ = first_dig;
  202. if (org_fmt == 'g') {
  203. prec += (e - 1);
  204. }
  205. // truncate precision to prevent buffer overflow
  206. if (prec + 2 > buf_remaining) {
  207. prec = buf_remaining - 2;
  208. }
  209. num_digits = prec;
  210. if (num_digits) {
  211. *s++ = '.';
  212. while (--e && num_digits) {
  213. *s++ = '0';
  214. num_digits--;
  215. }
  216. }
  217. } else {
  218. // For e & g formats, we'll be printing the exponent, so set the
  219. // sign.
  220. e_sign = e_sign_char;
  221. dec = 0;
  222. if (prec > (buf_remaining - FPMIN_BUF_SIZE)) {
  223. prec = buf_remaining - FPMIN_BUF_SIZE;
  224. if (fmt == 'g') {
  225. prec++;
  226. }
  227. }
  228. }
  229. } else {
  230. // Build positive exponent
  231. for (e = 0, e1 = FPDECEXP; e1; e1 >>= 1, pos_pow++, neg_pow++) {
  232. if (*pos_pow <= f) {
  233. e += e1;
  234. f *= *neg_pow;
  235. }
  236. }
  237. // It can be that f was right on the edge of an entry in pos_pow needs to be reduced
  238. if ((int)f >= 10) {
  239. e += 1;
  240. f *= FPCONST(0.1);
  241. }
  242. // If the user specified fixed format (fmt == 'f') and e makes the
  243. // number too big to fit into the available buffer, then we'll
  244. // switch to the 'e' format.
  245. if (fmt == 'f') {
  246. if (e >= buf_remaining) {
  247. fmt = 'e';
  248. } else if ((e + prec + 2) > buf_remaining) {
  249. prec = buf_remaining - e - 2;
  250. if (prec < 0) {
  251. // This means no decimal point, so we can add one back
  252. // for the decimal.
  253. prec++;
  254. }
  255. }
  256. }
  257. if (fmt == 'e' && prec > (buf_remaining - FPMIN_BUF_SIZE)) {
  258. prec = buf_remaining - FPMIN_BUF_SIZE;
  259. }
  260. if (fmt == 'g') {
  261. // Truncate precision to prevent buffer overflow
  262. if (prec + (FPMIN_BUF_SIZE - 1) > buf_remaining) {
  263. prec = buf_remaining - (FPMIN_BUF_SIZE - 1);
  264. }
  265. }
  266. // If the user specified 'g' format, and e is < prec, then we'll switch
  267. // to the fixed format.
  268. if (fmt == 'g' && e < prec) {
  269. fmt = 'f';
  270. prec -= (e + 1);
  271. }
  272. if (fmt == 'f') {
  273. dec = e;
  274. num_digits = prec + e + 1;
  275. } else {
  276. e_sign = '+';
  277. }
  278. }
  279. if (prec < 0) {
  280. // This can happen when the prec is trimmed to prevent buffer overflow
  281. prec = 0;
  282. }
  283. // We now have num.f as a floating point number between >= 1 and < 10
  284. // (or equal to zero), and e contains the absolute value of the power of
  285. // 10 exponent. and (dec + 1) == the number of dgits before the decimal.
  286. // For e, prec is # digits after the decimal
  287. // For f, prec is # digits after the decimal
  288. // For g, prec is the max number of significant digits
  289. //
  290. // For e & g there will be a single digit before the decimal
  291. // for f there will be e digits before the decimal
  292. if (fmt == 'e') {
  293. num_digits = prec + 1;
  294. } else if (fmt == 'g') {
  295. if (prec == 0) {
  296. prec = 1;
  297. }
  298. num_digits = prec;
  299. }
  300. // Print the digits of the mantissa
  301. for (int i = 0; i < num_digits; ++i, --dec) {
  302. int32_t d = (int32_t)f;
  303. if (d < 0) {
  304. *s++ = '0';
  305. } else {
  306. *s++ = '0' + d;
  307. }
  308. if (dec == 0 && prec > 0) {
  309. *s++ = '.';
  310. }
  311. f -= (FPTYPE)d;
  312. f *= FPCONST(10.0);
  313. }
  314. // Round
  315. // If we print non-exponential format (i.e. 'f'), but a digit we're going
  316. // to round by (e) is too far away, then there's nothing to round.
  317. if ((org_fmt != 'f' || e <= num_digits) && f >= FPCONST(5.0)) {
  318. char *rs = s;
  319. rs--;
  320. while (1) {
  321. if (*rs == '.') {
  322. rs--;
  323. continue;
  324. }
  325. if (*rs < '0' || *rs > '9') {
  326. // + or -
  327. rs++; // So we sit on the digit to the right of the sign
  328. break;
  329. }
  330. if (*rs < '9') {
  331. (*rs)++;
  332. break;
  333. }
  334. *rs = '0';
  335. if (rs == buf) {
  336. break;
  337. }
  338. rs--;
  339. }
  340. if (*rs == '0') {
  341. // We need to insert a 1
  342. if (rs[1] == '.' && fmt != 'f') {
  343. // We're going to round 9.99 to 10.00
  344. // Move the decimal point
  345. rs[0] = '.';
  346. rs[1] = '0';
  347. if (e_sign == '-') {
  348. e--;
  349. if (e == 0) {
  350. e_sign = '+';
  351. }
  352. } else {
  353. e++;
  354. }
  355. } else {
  356. // Need at extra digit at the end to make room for the leading '1'
  357. s++;
  358. }
  359. char *ss = s;
  360. while (ss > rs) {
  361. *ss = ss[-1];
  362. ss--;
  363. }
  364. *rs = '1';
  365. }
  366. }
  367. // verify that we did not overrun the input buffer so far
  368. assert((size_t)(s + 1 - buf) <= buf_size);
  369. if (org_fmt == 'g' && prec > 0) {
  370. // Remove trailing zeros and a trailing decimal point
  371. while (s[-1] == '0') {
  372. s--;
  373. }
  374. if (s[-1] == '.') {
  375. s--;
  376. }
  377. }
  378. // Append the exponent
  379. if (e_sign) {
  380. *s++ = e_char;
  381. *s++ = e_sign;
  382. if (FPMIN_BUF_SIZE == 7 && e >= 100) {
  383. *s++ = '0' + (e / 100);
  384. }
  385. *s++ = '0' + ((e / 10) % 10);
  386. *s++ = '0' + (e % 10);
  387. }
  388. *s = '\0';
  389. // verify that we did not overrun the input buffer
  390. assert((size_t)(s + 1 - buf) <= buf_size);
  391. return s - buf;
  392. }
  393. #endif // MICROPY_FLOAT_IMPL != MICROPY_FLOAT_IMPL_NONE