Skip to content

Commit bdc6e86

Browse files
committed
py/objfloat: Support raising a negative number to a fractional power.
This returns a complex number, following CPython behaviour. For ports that don't have complex numbers enabled this will raise a ValueError which gives a fail-safe for scripts that were written assuming complex numbers exist.
1 parent 62849b7 commit bdc6e86

File tree

2 files changed

+11
-0
lines changed

2 files changed

+11
-0
lines changed

py/objfloat.c

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -298,6 +298,13 @@ mp_obj_t mp_obj_float_binary_op(mp_binary_op_t op, mp_float_t lhs_val, mp_obj_t
298298
if (lhs_val == 0 && rhs_val < 0) {
299299
goto zero_division_error;
300300
}
301+
if (lhs_val < 0 && rhs_val != MICROPY_FLOAT_C_FUN(floor)(rhs_val)) {
302+
#if MICROPY_PY_BUILTINS_COMPLEX
303+
return mp_obj_complex_binary_op(MP_BINARY_OP_POWER, lhs_val, 0, rhs_in);
304+
#else
305+
mp_raise_ValueError("complex values not supported");
306+
#endif
307+
}
301308
lhs_val = MICROPY_FLOAT_C_FUN(pow)(lhs_val, rhs_val);
302309
break;
303310
case MP_BINARY_OP_DIVMOD: {

tests/float/complex1.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,10 @@
5353
# float on lhs should delegate to complex
5454
print(1.2 + 3j)
5555

56+
# negative base and fractional power should create a complex
57+
ans = (-1) ** 2.3; print("%.5g %.5g" % (ans.real, ans.imag))
58+
ans = (-1.2) ** -3.4; print("%.5g %.5g" % (ans.real, ans.imag))
59+
5660
# check printing of inf/nan
5761
print(float('nan') * 1j)
5862
print(float('inf') * (1 + 1j))

0 commit comments

Comments
 (0)