File tree Expand file tree Collapse file tree 1 file changed +12
-0
lines changed
Expand file tree Collapse file tree 1 file changed +12
-0
lines changed Original file line number Diff line number Diff line change @@ -203,6 +203,17 @@ export class PyComplexNumber {
203203 return `(${ this . toPythonComplexFloat ( this . real ) } ${ sign } ${ this . toPythonComplexFloat ( this . imag ) } j)` ;
204204 }
205205
206+ /*
207+ * This function converts the real and imaginary parts of a complex number into strings.
208+ * In Python, float values (used for the real and imaginary parts) are formatted using scientific
209+ * notation when their absolute value is less than 1e-4 or at least 1e16. TypeScript's default
210+ * formatting thresholds differ, so here we explicitly enforce Python's behavior.
211+ *
212+ * The chosen bounds (1e-4 and 1e16) are derived from Python's internal formatting logic
213+ * (refer to the `format_float_short` function in CPython's pystrtod.c
214+ * (https://github.com/python/cpython/blob/main/Python/pystrtod.c)). This ensures that the
215+ * output of py-slang more closely matches that of native Python.
216+ */
206217 private toPythonComplexFloat ( num : number ) {
207218 if ( num === Infinity ) {
208219 return "inf" ;
@@ -211,6 +222,7 @@ export class PyComplexNumber {
211222 return "-inf" ;
212223 }
213224
225+ // Force scientific notation for values < 1e-4 or ≥ 1e16 to mimic Python's float formatting behavior.
214226 if ( Math . abs ( num ) >= 1e16 || ( num !== 0 && Math . abs ( num ) < 1e-4 ) ) {
215227 return num . toExponential ( ) . replace ( / e ( [ + - ] ) ( \d ) $ / , 'e$10$2' ) ;
216228 }
You can’t perform that action at this time.
0 commit comments