8000 py/parsenum: Fix parsing of complex "j" and also "nanj", "infj". · micropython/micropython@61ce260 · GitHub
[go: up one dir, main page]

Skip to content

Commit 61ce260

Browse files
committed
py/parsenum: Fix parsing of complex "j" and also "nanj", "infj".
Prior to this commit, complex("j") would return 0j, and complex("nanj") would return nan+0j. This commit makes sure "j" is tested for after parsing the number (nan, inf or a decimal), and also supports the case of "j" on its own. Signed-off-by: Damien George <damien@micropython.org>
1 parent 0172292 commit 61ce260

File tree

2 files changed

+14
-3
lines changed

2 files changed

+14
-3
lines changed

py/parsenum.c

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -291,9 +291,6 @@ mp_obj_t mp_parse_num_decimal(const char *str, size_t len, bool allow_imag, bool
291291
if (str == top) {
292292
goto value_error;
293293
}
294-
} else if (allow_imag && (dig | 0x20) == 'j') {
295-
real_imag_state |= REAL_IMAG_STATE_HAVE_IMAG;
296-
break;
297294
} else if (dig == '_') {
298295
continue;
299296
} else {
@@ -327,6 +324,15 @@ mp_obj_t mp_parse_num_decimal(const char *str, size_t len, bool allow_imag, bool
327324
}
328325
}
329326

327+
if (allow_imag && str < top && (*str | 0x20) == 'j') {
328+
if (str == str_val_start) {
329+
// Convert "j" to "1j".
330+
dec_val = 1;
331+
}
332+
++str;
333+
real_imag_state |= REAL_IMAG_STATE_HAVE_IMAG;
334+
}
335+
330336
// negate value if needed
331337
if (dec_neg) {
332338
dec_val = -dec_val;

tests/float/complex1.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,19 @@
44
print(complex(1))
55
print(complex(1.2))
66
print(complex(1.2j))
7+
print(complex("j"))
8+
print(complex("J"))
79
print(complex("1"))
810
print(complex("1.2"))
911
print(complex("1.2j"))
12+
print(complex("1+j"))
1013
print(complex("1+2j"))
1114
print(complex("-1-2j"))
1215
print(complex("+1-2j"))
1316
print(complex(" -1-2j "))
1417
print(complex(" +1-2j "))
18+
print(complex("nanj"))
19+
print(complex("nan-infj"))
1520
print(complex(1, 2))
1621
print(complex(1j, 2j))
1722

0 commit comments

Comments
 (0)
0