blob: 21ed2d5508e63bf0fff8f5a71bba9e7b17691a93 [file] [log] [blame]
Damien George04b91472014-05-03 23:27:38 +01001/*
2 * This file is part of the Micro Python 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
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +020027#include "py/mpconfig.h"
28#if MICROPY_FLOAT_IMPL != MICROPY_FLOAT_IMPL_NONE
29
Damien Georgecea6cf82016-03-15 12:21:56 +000030#include <assert.h>
stijn861670b2015-05-16 10:54:19 +020031#include <stdlib.h>
32#include <stdint.h>
33#include "py/formatfloat.h"
34
Damien George8bfec2b2014-03-10 13:27:02 +000035/***********************************************************************
36
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +020037 Routine for converting a arbitrary floating
stijn861670b2015-05-16 10:54:19 +020038 point number into a string.
Damien George8bfec2b2014-03-10 13:27:02 +000039
Dave Hylandsca5a2412014-03-10 00:10:01 -070040 The code in this funcion was inspired from Fred Bayer's pdouble.c.
41 Since pdouble.c was released as Public Domain, I'm releasing this
42 code as public domain as well.
Damien George8bfec2b2014-03-10 13:27:02 +000043
Dave Hylandsca5a2412014-03-10 00:10:01 -070044 The original code can be found in https://github.com/dhylands/format-float
Damien George8bfec2b2014-03-10 13:27:02 +000045
Dave Hylandsca5a2412014-03-10 00:10:01 -070046 Dave Hylands
Damien George8bfec2b2014-03-10 13:27:02 +000047
Dave Hylandsca5a2412014-03-10 00:10:01 -070048***********************************************************************/
49
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +020050#if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT
Dave Hylandsca5a2412014-03-10 00:10:01 -070051// 1 sign bit, 8 exponent bits, and 23 mantissa bits.
52// exponent values 0 and 255 are reserved, exponent can be 1 to 254.
53// exponent is stored with a bias of 127.
54// The min and max floats are on the order of 1x10^37 and 1x10^-37
55
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +020056#define FPTYPE float
57#define FPCONST(x) x##F
58#define FPROUND_TO_ONE 0.9999995F
59#define FPDECEXP 32
Damien George7417ccf2016-01-29 11:39:12 +000060#define FPMIN_BUF_SIZE 6 // +9e+99
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +020061
Dave Hylandsca5a2412014-03-10 00:10:01 -070062#define FLT_SIGN_MASK 0x80000000
63#define FLT_EXP_MASK 0x7F800000
64#define FLT_MAN_MASK 0x007FFFFF
65
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +020066union floatbits {
67 float f;
68 uint32_t u;
69};
70static inline int fp_signbit(float x) { union floatbits fb = {x}; return fb.u & FLT_SIGN_MASK; }
71static inline int fp_isspecial(float x) { union floatbits fb = {x}; return (fb.u & FLT_EXP_MASK) == FLT_EXP_MASK; }
72static inline int fp_isinf(float x) { union floatbits fb = {x}; return (fb.u & FLT_MAN_MASK) == 0; }
73static inline int fp_iszero(float x) { union floatbits fb = {x}; return fb.u == 0; }
74static inline int fp_isless1(float x) { union floatbits fb = {x}; return fb.u < 0x3f800000; }
75// Assumes both fp_isspecial() and fp_isinf() were applied before
76#define fp_isnan(x) 1
77
78#elif MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE
79
80#define FPTYPE double
81#define FPCONST(x) x
82#define FPROUND_TO_ONE 0.999999999995
83#define FPDECEXP 256
Damien George7417ccf2016-01-29 11:39:12 +000084#define FPMIN_BUF_SIZE 7 // +9e+199
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +020085#include <math.h>
86#define fp_signbit(x) signbit(x)
87#define fp_isspecial(x) 1
88#define fp_isnan(x) isnan(x)
89#define fp_isinf(x) isinf(x)
90#define fp_iszero(x) (x == 0)
91#define fp_isless1(x) (x < 1.0)
92
93#endif
94
95static const FPTYPE g_pos_pow[] = {
96 #if FPDECEXP > 32
97 1e256, 1e128, 1e64,
98 #endif
Dave Hylandsca5a2412014-03-10 00:10:01 -070099 1e32, 1e16, 1e8, 1e4, 1e2, 1e1
100};
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200101static const FPTYPE g_neg_pow[] = {
102 #if FPDECEXP > 32
103 1e-256, 1e-128, 1e-64,
104 #endif
Dave Hylandsca5a2412014-03-10 00:10:01 -0700105 1e-32, 1e-16, 1e-8, 1e-4, 1e-2, 1e-1
106};
107
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200108int mp_format_float(FPTYPE f, char *buf, size_t buf_size, char fmt, int prec, char sign) {
Dave Hylandsca5a2412014-03-10 00:10:01 -0700109
110 char *s = buf;
Dave Hylandsca5a2412014-03-10 00:10:01 -0700111
Damien George7417ccf2016-01-29 11:39:12 +0000112 if (buf_size <= FPMIN_BUF_SIZE) {
113 // FPMIN_BUF_SIZE is the minimum size needed to store any FP number.
114 // If the buffer does not have enough room for this (plus null terminator)
115 // then don't try to format the float.
Dave Hylandsca5a2412014-03-10 00:10:01 -0700116
117 if (buf_size >= 2) {
118 *s++ = '?';
119 }
120 if (buf_size >= 1) {
121 *s++ = '\0';
122 }
123 return buf_size >= 2;
124 }
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200125 if (fp_signbit(f)) {
Dave Hylandsca5a2412014-03-10 00:10:01 -0700126 *s++ = '-';
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200127 f = -f;
Dave Hylandsca5a2412014-03-10 00:10:01 -0700128 } else {
129 if (sign) {
130 *s++ = sign;
131 }
132 }
Damien George7417ccf2016-01-29 11:39:12 +0000133
134 // buf_remaining contains bytes available for digits and exponent.
135 // It is buf_size minus room for the sign and null byte.
136 int buf_remaining = buf_size - 1 - (s - buf);
Dave Hylandsca5a2412014-03-10 00:10:01 -0700137
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200138 if (fp_isspecial(f)) {
Dave Hylandsca5a2412014-03-10 00:10:01 -0700139 char uc = fmt & 0x20;
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200140 if (fp_isinf(f)) {
Dave Hylandsca5a2412014-03-10 00:10:01 -0700141 *s++ = 'I' ^ uc;
142 *s++ = 'N' ^ uc;
143 *s++ = 'F' ^ uc;
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200144 goto ret;
145 } else if (fp_isnan(f)) {
Dave Hylandsca5a2412014-03-10 00:10:01 -0700146 *s++ = 'N' ^ uc;
147 *s++ = 'A' ^ uc;
148 *s++ = 'N' ^ uc;
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200149 ret:
150 *s = '\0';
151 return s - buf;
Dave Hylandsca5a2412014-03-10 00:10:01 -0700152 }
Dave Hylandsca5a2412014-03-10 00:10:01 -0700153 }
154
155 if (prec < 0) {
156 prec = 6;
157 }
158 char e_char = 'E' | (fmt & 0x20); // e_char will match case of fmt
159 fmt |= 0x20; // Force fmt to be lowercase
160 char org_fmt = fmt;
161 if (fmt == 'g' && prec == 0) {
162 prec = 1;
163 }
164 int e, e1;
165 int dec = 0;
166 char e_sign = '\0';
167 int num_digits = 0;
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200168 const FPTYPE *pos_pow = g_pos_pow;
169 const FPTYPE *neg_pow = g_neg_pow;
Dave Hylandsca5a2412014-03-10 00:10:01 -0700170
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200171 if (fp_iszero(f)) {
Dave Hylandsca5a2412014-03-10 00:10:01 -0700172 e = 0;
173 if (fmt == 'e') {
174 e_sign = '+';
175 } else if (fmt == 'f') {
176 num_digits = prec + 1;
177 }
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200178 } else if (fp_isless1(f)) {
Paul Sokolovsky3d6240b2015-11-22 20:02:16 +0200179 // We need to figure out what an integer digit will be used
180 // in case 'f' is used (or we revert other format to it below).
181 // As we just tested number to be <1, this is obviously 0,
182 // but we can round it up to 1 below.
183 char first_dig = '0';
184 if (f >= FPROUND_TO_ONE) {
185 first_dig = '1';
186 }
187
Dave Hylandsca5a2412014-03-10 00:10:01 -0700188 // Build negative exponent
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200189 for (e = 0, e1 = FPDECEXP; e1; e1 >>= 1, pos_pow++, neg_pow++) {
190 if (*neg_pow > f) {
Dave Hylandsca5a2412014-03-10 00:10:01 -0700191 e += e1;
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200192 f *= *pos_pow;
Dave Hylandsca5a2412014-03-10 00:10:01 -0700193 }
194 }
Dave Hylandsb2178692015-04-12 00:36:00 -0700195 char e_sign_char = '-';
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200196 if (fp_isless1(f) && f >= FPROUND_TO_ONE) {
197 f = FPCONST(1.0);
Dave Hylandsb2178692015-04-12 00:36:00 -0700198 if (e == 0) {
199 e_sign_char = '+';
200 }
Damien George03b8bb72016-03-29 22:03:13 +0100201 } else if (fp_isless1(f)) {
Dave Hylandsca5a2412014-03-10 00:10:01 -0700202 e++;
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200203 f *= FPCONST(10.0);
Dave Hylandsca5a2412014-03-10 00:10:01 -0700204 }
205
206 // If the user specified 'g' format, and e is <= 4, then we'll switch
207 // to the fixed format ('f')
208
209 if (fmt == 'f' || (fmt == 'g' && e <= 4)) {
210 fmt = 'f';
211 dec = -1;
Dave Hylandsb2178692015-04-12 00:36:00 -0700212 *s++ = first_dig;
Dave Hylandsca5a2412014-03-10 00:10:01 -0700213
Dave Hylandsca5a2412014-03-10 00:10:01 -0700214 if (org_fmt == 'g') {
215 prec += (e - 1);
216 }
Damien Georgecea6cf82016-03-15 12:21:56 +0000217
218 // truncate precision to prevent buffer overflow
219 if (prec + 2 > buf_remaining) {
220 prec = buf_remaining - 2;
221 }
222
Dave Hylandsca5a2412014-03-10 00:10:01 -0700223 num_digits = prec;
224 if (num_digits) {
225 *s++ = '.';
226 while (--e && num_digits) {
227 *s++ = '0';
228 num_digits--;
229 }
230 }
231 } else {
232 // For e & g formats, we'll be printing the exponent, so set the
233 // sign.
Dave Hylandsb2178692015-04-12 00:36:00 -0700234 e_sign = e_sign_char;
Dave Hylandsca5a2412014-03-10 00:10:01 -0700235 dec = 0;
236
Damien George7417ccf2016-01-29 11:39:12 +0000237 if (prec > (buf_remaining - FPMIN_BUF_SIZE)) {
238 prec = buf_remaining - FPMIN_BUF_SIZE;
Dave Hylandsca5a2412014-03-10 00:10:01 -0700239 if (fmt == 'g') {
240 prec++;
241 }
242 }
243 }
244 } else {
245 // Build positive exponent
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200246 for (e = 0, e1 = FPDECEXP; e1; e1 >>= 1, pos_pow++, neg_pow++) {
247 if (*pos_pow <= f) {
Dave Hylandsca5a2412014-03-10 00:10:01 -0700248 e += e1;
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200249 f *= *neg_pow;
Dave Hylandsca5a2412014-03-10 00:10:01 -0700250 }
251 }
252
Damien George03b8bb72016-03-29 22:03:13 +0100253 // It can be that f was right on the edge of an entry in pos_pow needs to be reduced
254 if (f >= FPCONST(10.0)) {
255 e += 1;
256 f *= FPCONST(0.1);
257 }
258
Dave Hylandsca5a2412014-03-10 00:10:01 -0700259 // If the user specified fixed format (fmt == 'f') and e makes the
260 // number too big to fit into the available buffer, then we'll
261 // switch to the 'e' format.
262
263 if (fmt == 'f') {
264 if (e >= buf_remaining) {
265 fmt = 'e';
266 } else if ((e + prec + 2) > buf_remaining) {
267 prec = buf_remaining - e - 2;
268 if (prec < 0) {
269 // This means no decimal point, so we can add one back
270 // for the decimal.
271 prec++;
272 }
273 }
274 }
Damien George7417ccf2016-01-29 11:39:12 +0000275 if (fmt == 'e' && prec > (buf_remaining - FPMIN_BUF_SIZE)) {
276 prec = buf_remaining - FPMIN_BUF_SIZE;
Dave Hylandsca5a2412014-03-10 00:10:01 -0700277 }
278 // If the user specified 'g' format, and e is < prec, then we'll switch
279 // to the fixed format.
280
281 if (fmt == 'g' && e < prec) {
282 fmt = 'f';
283 prec -= (e + 1);
284 }
285 if (fmt == 'f') {
286 dec = e;
287 num_digits = prec + e + 1;
288 } else {
289 e_sign = '+';
290 }
291 }
292 if (prec < 0) {
293 // This can happen when the prec is trimmed to prevent buffer overflow
294 prec = 0;
295 }
296
297 // We now have num.f as a floating point number between >= 1 and < 10
298 // (or equal to zero), and e contains the absolute value of the power of
299 // 10 exponent. and (dec + 1) == the number of dgits before the decimal.
300
301 // For e, prec is # digits after the decimal
302 // For f, prec is # digits after the decimal
303 // For g, prec is the max number of significant digits
304 //
305 // For e & g there will be a single digit before the decimal
306 // for f there will be e digits before the decimal
307
308 if (fmt == 'e') {
309 num_digits = prec + 1;
310 } else if (fmt == 'g') {
311 if (prec == 0) {
312 prec = 1;
313 }
314 num_digits = prec;
315 }
316
317 // Print the digits of the mantissa
318 for (int i = 0; i < num_digits; ++i, --dec) {
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200319 int32_t d = f;
Dave Hylandsca5a2412014-03-10 00:10:01 -0700320 *s++ = '0' + d;
321 if (dec == 0 && prec > 0) {
322 *s++ = '.';
323 }
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200324 f -= (FPTYPE)d;
325 f *= FPCONST(10.0);
Dave Hylandsca5a2412014-03-10 00:10:01 -0700326 }
327
328 // Round
Paul Sokolovsky3c4c0692015-11-22 18:09:28 +0200329 // If we print non-exponential format (i.e. 'f'), but a digit we're going
330 // to round by (e) is too far away, then there's nothing to round.
331 if ((org_fmt != 'f' || e <= 1) && f >= FPCONST(5.0)) {
Dave Hylandsca5a2412014-03-10 00:10:01 -0700332 char *rs = s;
333 rs--;
334 while (1) {
335 if (*rs == '.') {
336 rs--;
337 continue;
338 }
339 if (*rs < '0' || *rs > '9') {
340 // + or -
341 rs++; // So we sit on the digit to the right of the sign
342 break;
343 }
344 if (*rs < '9') {
345 (*rs)++;
346 break;
347 }
348 *rs = '0';
349 if (rs == buf) {
350 break;
351 }
352 rs--;
353 }
354 if (*rs == '0') {
355 // We need to insert a 1
356 if (rs[1] == '.' && fmt != 'f') {
357 // We're going to round 9.99 to 10.00
358 // Move the decimal point
359 rs[0] = '.';
360 rs[1] = '0';
361 if (e_sign == '-') {
362 e--;
363 } else {
364 e++;
365 }
366 }
367 s++;
368 char *ss = s;
369 while (ss > rs) {
370 *ss = ss[-1];
371 ss--;
372 }
373 *rs = '1';
374 }
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200375 if (fp_isless1(f) && fmt == 'f') {
Dave Hylandsca5a2412014-03-10 00:10:01 -0700376 // We rounded up to 1.0
377 prec--;
378 }
379 }
380
381 if (org_fmt == 'g' && prec > 0) {
382 // Remove trailing zeros and a trailing decimal point
383 while (s[-1] == '0') {
384 s--;
385 }
386 if (s[-1] == '.') {
387 s--;
388 }
389 }
390 // Append the exponent
391 if (e_sign) {
392 *s++ = e_char;
393 *s++ = e_sign;
Damien George7417ccf2016-01-29 11:39:12 +0000394 if (FPMIN_BUF_SIZE == 7 && e >= 100) {
395 *s++ = '0' + (e / 100);
396 }
397 *s++ = '0' + ((e / 10) % 10);
Dave Hylandsca5a2412014-03-10 00:10:01 -0700398 *s++ = '0' + (e % 10);
399 }
400 *s = '\0';
401
Damien Georgecea6cf82016-03-15 12:21:56 +0000402 // verify that we did not overrun the input buffer
403 assert((size_t)(s + 1 - buf) <= buf_size);
404
Dave Hylandsca5a2412014-03-10 00:10:01 -0700405 return s - buf;
406}
407
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200408#endif // MICROPY_FLOAT_IMPL != MICROPY_FLOAT_IMPL_NONE