-
Notifications
You must be signed in to change notification settings - Fork 1.7k
fix(vars): match Python round semantics #6769
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| `NumberVar` rounding now matches Python's round-half-even behavior and supports negative `ndigits` values in compiled frontend expressions. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,43 @@ | ||
| /** | ||
| * Round a number using Python's round-half-even semantics. | ||
| * Decompose the IEEE 754 value into a rational so ties are compared exactly. | ||
| * | ||
| * @param {number} value The value to round. | ||
| * @param {number} ndigits The decimal precision. | ||
| * @returns {number} The rounded value. | ||
| */ | ||
| export default function pyRound(value, ndigits) { | ||
| if (!Number.isFinite(value) || ndigits > 323) return value; | ||
| if (ndigits < -308) return value * 0; | ||
|
|
||
| const view = new DataView(new ArrayBuffer(8)); | ||
| view.setFloat64(0, Math.abs(value)); | ||
| const bits = view.getBigUint64(0); | ||
| const exponent = Number((bits >> 52n) & 0x7ffn); | ||
| const fraction = bits & 0xfffffffffffffn; | ||
| const significand = exponent === 0 ? fraction : fraction | 0x10000000000000n; | ||
| const binaryExponent = exponent === 0 ? -1074 : exponent - 1075; | ||
| const fivePower = 5n ** BigInt(Math.abs(ndigits)); | ||
|
|
||
| let numerator = significand * (ndigits >= 0 ? fivePower : 1n); | ||
| let denominator = ndigits < 0 ? fivePower : 1n; | ||
| const shift = binaryExponent + ndigits; | ||
| if (shift >= 0) { | ||
| numerator <<= BigInt(shift); | ||
| } else { | ||
| denominator <<= BigInt(-shift); | ||
| } | ||
|
|
||
| let rounded = numerator / denominator; | ||
| const doubledRemainder = (numerator % denominator) * 2n; | ||
| if ( | ||
| doubledRemainder > denominator || | ||
| (doubledRemainder === denominator && rounded % 2n === 1n) | ||
| ) { | ||
| rounded += 1n; | ||
| } | ||
|
|
||
| const sign = value < 0 || Object.is(value, -0) ? "-" : ""; | ||
| const result = Number(`${sign}${rounded}e${-ndigits}`); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
When rounding very large finite values with negative precisions near Useful? React with 👍 / 👎. |
||
| return result === 0 && sign ? -0 : result; | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -2,8 +2,10 @@ | |
| import json | ||
| import math | ||
| import re | ||
| import subprocess | ||
| import typing | ||
| from collections.abc import Mapping, Sequence | ||
| from pathlib import Path | ||
| from typing import cast | ||
|
|
||
| import pytest | ||
|
|
@@ -54,9 +56,14 @@ | |
|
|
||
| pytest.importorskip("pydantic") | ||
|
|
||
|
|
||
| from pydantic import BaseModel as Base | ||
|
|
||
| ROUND_HELPER = ( | ||
| Path(__file__).parents[2] | ||
| / "packages/reflex-base/src/reflex_base/.templates/web/utils/helpers/round.js" | ||
| ) | ||
|
|
||
|
|
||
| test_vars = [ | ||
| Var(_js_expr="prop1", _var_type=int), | ||
| Var(_js_expr="key", _var_type=str), | ||
|
|
@@ -1038,7 +1045,7 @@ def test_all_number_operations(): | |
|
|
||
| assert ( | ||
| str(even_more_complicated_number) | ||
| == "!(isTrue(pyOr(Math.abs(Math.floor(((Math.floor(((-((-5.4 + 1)) * 2) / 3) / 2) % 3) ** 2))), () => (pyAnd(2, () => (Math.round(((Math.floor(((-((-5.4 + 1)) * 2) / 3) / 2) % 3) ** 2))))))))" | ||
| == "!(isTrue(pyOr(Math.abs(Math.floor(((Math.floor(((-((-5.4 + 1)) * 2) / 3) / 2) % 3) ** 2))), () => (pyAnd(2, () => (pyRound(((Math.floor(((-((-5.4 + 1)) * 2) / 3) / 2) % 3) ** 2), 0)))))))" | ||
| ) | ||
|
|
||
| assert str(LiteralNumberVar.create(5) > False) == "(5 > 0)" | ||
|
|
@@ -1049,6 +1056,51 @@ def test_all_number_operations(): | |
| ) | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| ("value", "ndigits", "expected"), | ||
| [ | ||
| (2.5, 0, "2"), | ||
| (3.5, 0, "4"), | ||
| (-2.5, 0, "-2"), | ||
| (-3.5, 0, "-4"), | ||
| (3.6, 0, "4"), | ||
| (250, -2, "200"), | ||
| (350, -2, "400"), | ||
| (-250, -2, "-200"), | ||
| (-350, -2, "-400"), | ||
| (2.675, 2, "2.67"), | ||
| (5e-324, 323, "0"), | ||
| (1e20, 0, "100000000000000000000"), | ||
| (1.2345, 324, "1.2345"), | ||
| (-1.2345, -309, "-0"), | ||
| (float("inf"), 2, "Infinity"), | ||
| ], | ||
| ) | ||
| def test_number_round_python_semantics(value, ndigits, expected): | ||
| rounded = round(LiteralNumberVar.create(value), ndigits) | ||
| var_data = rounded._get_all_var_data() | ||
| assert var_data is not None | ||
| assert any( | ||
| imported.tag == "pyRound" and imported.is_default | ||
| for imported in dict(var_data.imports)["$/utils/helpers/round.js"] | ||
| ) | ||
|
|
||
| result = subprocess.run( | ||
| [ | ||
| "node", | ||
| "--input-type=module", | ||
| "--eval", | ||
| f"{ROUND_HELPER.read_text(encoding='utf-8')}\nconsole.log({rounded!s})", | ||
| ], | ||
| check=True, | ||
|
Comment on lines
+1075
to
+1095
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
The parametrized test spawns Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time! |
||
| capture_output=True, | ||
| text=True, | ||
| ) | ||
|
|
||
| assert result.stdout.strip() == expected | ||
| assert rounded._var_type is (int if ndigits == 0 else float) | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| ("var", "expected"), | ||
| [ | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ndigitsvaluesBigInt()throws aRangeErrorfor non-integer floats (e.g.BigInt(2.5)→RangeError). Becauseshift = binaryExponent + ndigits(line 24) usesndigitsdirectly, any fractionalndigits— such as a Reflex state variable typed asfloatwith a non-integer runtime value like2.5— would causeBigInt(shift)to throw and crash the frontend render. Addingif (!Number.isInteger(ndigits)) return value;after the existing early-return guards would make the function robust against this class of misuse.