The animation engine for agents: blazingly fast math and 3D videos with Manim's Python API, on a Rust GPU core.
Python
Number a line's ticks with the decimal places they need
Don Yin1fb4dd7327bf
diff --git a/docs/content/changelog.md b/docs/content/changelog.mdindex 814d2fab..938349a0 100644--- a/docs/content/changelog.md+++ b/docs/content/changelog.md@@ -45,6 +45,7 @@ The notable changes to ManimGX, release by release. The format follows### Fixed+- Number a line's ticks with the decimal places they need: a range on one side of 0 that starts between whole numbers, such as `NumberLine((3.5, 7.5, 1))`, was numbered 4, 4, 6, 6, 8, where its ticks are at 3.5, 4.5, …; a step written with an exponent (`1e-05`) gave no places, and one with round-off (`0.1 + 0.2`) gave 17.- Give a type checker the package's names: each module lists the names it gives in `__all__`, and each package takes in its children's and gathers their lists, so `m.Scene`, `m.Text`, `m.config` and every other name are the package's, where they were reported as not exported ([#38](https://github.com/academa-labs/manimgx/issues/38)). `from manimgx import *` binds exactly those names, no longer the package's modules too: `manimgx.typing` took the place of the standard library's `typing`.- Redraw a shape that empties with `always_redraw` without a RecursionError, and keep a mobject's updaters off the member its points move into when a transform aligns it, so a relative updater such as `always_shift` no longer runs twice on them ([#32](https://github.com/academa-labs/manimgx/issues/32)).- Measure a text's size in `inspect` and `render` at 1080p, which is 1080 px on a video's short side, so a tall video (1080x1920) no longer reports readable text as small ([#37](https://github.com/academa-labs/manimgx/issues/37)).diff --git a/src/manimgx/mobjects/plotting.py b/src/manimgx/mobjects/plotting.pyindex 14fd1385..2983d212 100644--- a/src/manimgx/mobjects/plotting.py+++ b/src/manimgx/mobjects/plotting.py@@ -727,7 +727,8 @@ class NumberLineOptions(_Tipped, total=False, closed=True):"""The gap between the line and its numbers, in scene units (default 0.25)."""decimal_number_config: DecimalNumberOptions | None"""[Number keywords][manimgx.DecimalNumber] for the- numbers (default None: as many decimal places as the range's step has)."""+ numbers (default None: as many decimal places as the range's step has, or its+ start, when the range is all on one side of 0)."""numbers_to_exclude: Iterable[float] | None"""Numbers not to write, when the ticks are numbered (default None: none; anaxis's leave out 0)."""@@ -801,7 +802,8 @@ class NumberLine(Line):line_to_number_buff: The gap between the line and its numbers, in scene units.decimal_number_config: The numbers'[number keywords][manimgx.DecimalNumber]; None- for as many decimal places as `x_step` has.+ for as many decimal places as `x_step` has, or the range's start, when+ the range is all on one side of 0 and its ticks count from there.numbers_to_exclude: Numbers not to write, when the ticks are numbered; Nonefor none.numbers_to_include: The numbers to write, instead of the ticks': given, they@@ -883,9 +885,15 @@ class NumberLine(Line):elif len(x_range) == 2:x_range = [*x_range, 1]if decimal_number_config is None:- decimal_number_config = {- "num_decimal_places": self._decimal_places_from_step(x_range[2])- }+ # a whole float step keeps its one place: (0, 3, 1.0) is written 1.0, 2.0+ places = max(+ self._decimal_places_of(x_range[2]),+ int(str(x_range[2]).endswith(".0")),+ )+ if 0 < x_range[0] < x_range[1] or x_range[0] < x_range[1] < 0:+ # ticks count from the start, not from 0 (see get_tick_range)+ places = max(places, self._decimal_places_of(x_range[0]))+ decimal_number_config = {"num_decimal_places": places}self.x_range = np.array(x_range, dtype=float)"""The line's range, `[x_min, x_max, x_step]`, as given: of exponents, on alogarithmic line."""@@ -1301,11 +1309,20 @@ class NumberLine(Line):return label_constructor(str(label_tex), **kwargs)@staticmethod- def _decimal_places_from_step(step: float) -> int:- step_str = str(step)- if "." not in step_str:- return 0- return len(step_str.split(".")[-1])+ def _decimal_places_of(value: float) -> int:+ """The decimal places a number is written with, to 15 significant digits.++ Fifteen digits leave out a float's round-off (0.1 + 0.2 has one place) and+ read an exponent (1e-05 has five); a whole number has none.++ Args:+ value: The number.++ Returns:+ How many decimal places it has.+ """+ mantissa, _, exponent = f"{value:.15g}".partition("e")+ return max(0, len(mantissa.partition(".")[2]) - int(exponent or 0))class UnitInterval(NumberLine):diff --git a/tests/unit/mobjects/test_plotting.py b/tests/unit/mobjects/test_plotting.pyindex 937f60aa..26e8e08b 100644--- a/tests/unit/mobjects/test_plotting.py+++ b/tests/unit/mobjects/test_plotting.py@@ -155,6 +155,53 @@ def test_ticks_and_numbers_added_later_follow_the_lines_attributes() -> None:assert line.get_unit_vector()[0] == pytest.approx(line.unit_size)+ ("x_range", "values", "places"),+ [+ ((3.5, 7.5, 1), [3.5, 4.5, 5.5, 6.5, 7.5], 1), # (was 4 4 6 6 8)+ ((-7.5, -3.5, 1), [-7.5, -6.5, -5.5, -4.5, -3.5], 1),+ ((3.25, 5.25, 1), [3.25, 4.25, 5.25], 2),+ ((0, 4e-5, 1e-5), [0, 1e-5, 2e-5, 3e-5, 4e-5], 5), # (was 0 0 0 0 0)+ ((0, 1.2, 0.1 + 0.2), [0, 0.3, 0.6, 0.9, 1.2], 1), # (not 17 places)+ ],+)+def test_numbers_have_the_places_their_ticks_need(+ x_range: tuple[float, float, float], values: list[float], places: int+) -> None:+ line = m.NumberLine(x_range, include_numbers=True)+ numbers = list(line.numbers)+ assert all(isinstance(number, m.DecimalNumber) for number in numbers)+ numbers = [number for number in numbers if isinstance(number, m.DecimalNumber)]+ np.testing.assert_allclose(+ [number.get_value() for number in numbers], values, atol=1e-12+ )+ assert [number.num_decimal_places for number in numbers] == [places] * len(values)+++ ("x_range", "places"),+ [+ ((-3.5, 3.5, 1), 0), # ticks count from 0+ ((-3.5, 0, 1), 0),+ ((3, 7.5, 1), 0), # the end is not a tick+ ((2.0, 5, 1), 0),+ ((0, 3, 1.0), 1), # a whole float step, as before+ ((0, 3, 1), 0),+ ((1e20, 3e20, 1e20), 0),+ ],+)+def test_places_are_unchanged_where_ticks_are_whole(+ x_range: tuple[float, float, float], places: int+) -> None:+ line = m.NumberLine(x_range, include_ticks=False)+ assert line.decimal_number_config == {"num_decimal_places": places}+++def test_given_places_win_over_the_ranges() -> None:+ line = m.NumberLine((3.5, 7.5, 1), decimal_number_config={"num_decimal_places": 0})+ assert line.decimal_number_config == {"num_decimal_places": 0}++FUNCTIONS: dict[str, Callable[[float], float]] = {"a square": lambda t: t * t,"a wave": lambda t: np.sin(3 * t) + t,