Skip to content

Commit f3b66ef

Browse files
WangdahaiWangdahai
authored andcommitted
add commend on double to string
1 parent 09a879f commit f3b66ef

File tree

1 file changed

+12
-0
lines changed

1 file changed

+12
-0
lines changed

src/types.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff 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
}

0 commit comments

Comments
 (0)