blob: f7762b07dd3e309dcf598c434291229452458ab3 [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 }
Dave Hylandsca5a2412014-03-10 00:10:01 -0700201 } else {
202 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
253 // If the user specified fixed format (fmt == 'f') and e makes the
254 // number too big to fit into the available buffer, then we'll
255 // switch to the 'e' format.
256
257 if (fmt == 'f') {
258 if (e >= buf_remaining) {
259 fmt = 'e';
260 } else if ((e + prec + 2) > buf_remaining) {
261 prec = buf_remaining - e - 2;
262 if (prec < 0) {
263 // This means no decimal point, so we can add one back
264 // for the decimal.
265 prec++;
266 }
267 }
268 }
Damien George7417ccf2016-01-29 11:39:12 +0000269 if (fmt == 'e' && prec > (buf_remaining - FPMIN_BUF_SIZE)) {
270 prec = buf_remaining - FPMIN_BUF_SIZE;
Dave Hylandsca5a2412014-03-10 00:10:01 -0700271 }
272 // If the user specified 'g' format, and e is < prec, then we'll switch
273 // to the fixed format.
274
275 if (fmt == 'g' && e < prec) {
276 fmt = 'f';
277 prec -= (e + 1);
278 }
279 if (fmt == 'f') {
280 dec = e;
281 num_digits = prec + e + 1;
282 } else {
283 e_sign = '+';
284 }
285 }
286 if (prec < 0) {
287 // This can happen when the prec is trimmed to prevent buffer overflow
288 prec = 0;
289 }
290
291 // We now have num.f as a floating point number between >= 1 and < 10
292 // (or equal to zero), and e contains the absolute value of the power of
293 // 10 exponent. and (dec + 1) == the number of dgits before the decimal.
294
295 // For e, prec is # digits after the decimal
296 // For f, prec is # digits after the decimal
297 // For g, prec is the max number of significant digits
298 //
299 // For e & g there will be a single digit before the decimal
300 // for f there will be e digits before the decimal
301
302 if (fmt == 'e') {
303 num_digits = prec + 1;
304 } else if (fmt == 'g') {
305 if (prec == 0) {
306 prec = 1;
307 }
308 num_digits = prec;
309 }
310
311 // Print the digits of the mantissa
312 for (int i = 0; i < num_digits; ++i, --dec) {
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200313 int32_t d = f;
Dave Hylandsca5a2412014-03-10 00:10:01 -0700314 *s++ = '0' + d;
315 if (dec == 0 && prec > 0) {
316 *s++ = '.';
317 }
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200318 f -= (FPTYPE)d;
319 f *= FPCONST(10.0);
Dave Hylandsca5a2412014-03-10 00:10:01 -0700320 }
321
322 // Round
Paul Sokolovsky3c4c0692015-11-22 18:09:28 +0200323 // If we print non-exponential format (i.e. 'f'), but a digit we're going
324 // to round by (e) is too far away, then there's nothing to round.
325 if ((org_fmt != 'f' || e <= 1) && f >= FPCONST(5.0)) {
Dave Hylandsca5a2412014-03-10 00:10:01 -0700326 char *rs = s;
327 rs--;
328 while (1) {
329 if (*rs == '.') {
330 rs--;
331 continue;
332 }
333 if (*rs < '0' || *rs > '9') {
334 // + or -
335 rs++; // So we sit on the digit to the right of the sign
336 break;
337 }
338 if (*rs < '9') {
339 (*rs)++;
340 break;
341 }
342 *rs = '0';
343 if (rs == buf) {
344 break;
345 }
346 rs--;
347 }
348 if (*rs == '0') {
349 // We need to insert a 1
350 if (rs[1] == '.' && fmt != 'f') {
351 // We're going to round 9.99 to 10.00
352 // Move the decimal point
353 rs[0] = '.';
354 rs[1] = '0';
355 if (e_sign == '-') {
356 e--;
357 } else {
358 e++;
359 }
360 }
361 s++;
362 char *ss = s;
363 while (ss > rs) {
364 *ss = ss[-1];
365 ss--;
366 }
367 *rs = '1';
368 }
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200369 if (fp_isless1(f) && fmt == 'f') {
Dave Hylandsca5a2412014-03-10 00:10:01 -0700370 // We rounded up to 1.0
371 prec--;
372 }
373 }
374
375 if (org_fmt == 'g' && prec > 0) {
376 // Remove trailing zeros and a trailing decimal point
377 while (s[-1] == '0') {
378 s--;
379 }
380 if (s[-1] == '.') {
381 s--;
382 }
383 }
384 // Append the exponent
385 if (e_sign) {
386 *s++ = e_char;
387 *s++ = e_sign;
Damien George7417ccf2016-01-29 11:39:12 +0000388 if (FPMIN_BUF_SIZE == 7 && e >= 100) {
389 *s++ = '0' + (e / 100);
390 }
391 *s++ = '0' + ((e / 10) % 10);
Dave Hylandsca5a2412014-03-10 00:10:01 -0700392 *s++ = '0' + (e % 10);
393 }
394 *s = '\0';
395
Damien Georgecea6cf82016-03-15 12:21:56 +0000396 // verify that we did not overrun the input buffer
397 assert((size_t)(s + 1 - buf) <= buf_size);
398
Dave Hylandsca5a2412014-03-10 00:10:01 -0700399 return s - buf;
400}
401
Paul Sokolovsky9aaccd42015-11-22 15:42:09 +0200402#endif // MICROPY_FLOAT_IMPL != MICROPY_FLOAT_IMPL_NONE