-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_scenes.py
More file actions
816 lines (687 loc) · 33.7 KB
/
Copy pathbinary_scenes.py
File metadata and controls
816 lines (687 loc) · 33.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from manim import *
from manim_helpers import maths_text
ROW_GAP = 0.55
FONT_SIZE = 28
BIT_FONT_SIZE = 24
LABEL_WIDTH = 2.35
OP_WIDTH = 0.8
CARRY_WIDTH = 0.55
EXP_WIDTH = 1.05
ROW_HEIGHT = 0.52
@dataclass(frozen=True)
class BinaryField:
label: str
bits: str
@dataclass(frozen=True)
class FloatingPointComponents:
fixed_value: str
fixed_bits: str
fixed_value_numeric: float
mantissa_bits: str
exponent_value: int
exponent_bits: str
floating_value: float
precision_loss: float
def _bit_group(bits: str) -> VGroup:
cells = VGroup()
for bit in bits:
cell = RoundedRectangle(corner_radius=0.08, width=0.44, height=0.44, stroke_width=2)
cell.set_stroke(color=WHITE, opacity=0.75)
cell.set_fill(BLACK, opacity=0)
cell.add(maths_text(bit, font_size=BIT_FONT_SIZE).move_to(cell))
cells.add(cell)
cells.arrange(RIGHT, buff=0.07)
return cells
def _field_row(field: BinaryField) -> VGroup:
label = Text(field.label, font_size=FONT_SIZE)
bits = _bit_group(field.bits)
return VGroup(label, bits).arrange(RIGHT, buff=0.35, aligned_edge=UP)
def _align_rows(rows: VGroup) -> None:
ref = max(rows, key=lambda row: row[1].width)
for row in rows:
row[1].align_to(ref[1], RIGHT)
def _binary_bits(value: int, bits: int) -> str:
return format(value & ((1 << bits) - 1), f"0{bits}b")
def _twos_complement_bits(value: int, bits: int) -> str:
return _binary_bits((1 << bits) - value, bits)
def _fixed_from_denary_value(denary_value: float, integer_bits: int, fraction_bits: int) -> tuple[str, str]:
if denary_value < 0:
raise ValueError("Fixed-point conversion currently supports non-negative denary inputs only")
total_bits = integer_bits + fraction_bits
scale = 1 << fraction_bits
scaled = int(round(denary_value * scale))
max_scaled = (1 << total_bits) - 1
if scaled > max_scaled:
raise ValueError(
f"Denary value {denary_value:g} does not fit in {integer_bits}.{fraction_bits} fixed-point bits"
)
fixed_bits = format(scaled, f"0{total_bits}b")
fixed_value = f"{fixed_bits[:integer_bits]}.{fixed_bits[integer_bits:]}"
return fixed_value, fixed_bits
def _floating_point_components(
denary_value: float,
integer_bits: int,
fraction_bits: int,
mantissa_bits: int,
exponent_bits: int,
exponent: int | None = None,
) -> FloatingPointComponents:
fixed_value, fixed_bits = _fixed_from_denary_value(denary_value, integer_bits, fraction_bits)
first_one_index = fixed_bits.find("1")
if first_one_index == -1:
auto_exponent = 0
mantissa_source = "0" * mantissa_bits
else:
auto_exponent = integer_bits - first_one_index
mantissa_source = "0" + fixed_bits[first_one_index:] + ("0" * mantissa_bits)
mantissa = mantissa_source[:mantissa_bits]
exponent_value = exponent if exponent is not None else auto_exponent
exponent_value_bits = format(exponent_value & ((1 << exponent_bits) - 1), f"0{exponent_bits}b")
fixed_value_numeric = int(fixed_bits, 2) / float(1 << fraction_bits)
sign = -1.0 if mantissa[0] == "1" else 1.0
mantissa_fraction = 0.0
for bit_index, bit in enumerate(mantissa[1:], start=1):
if bit == "1":
mantissa_fraction += 2 ** (-bit_index)
floating_value = sign * mantissa_fraction * (2**exponent_value)
return FloatingPointComponents(
fixed_value=fixed_value,
fixed_bits=fixed_bits,
fixed_value_numeric=fixed_value_numeric,
mantissa_bits=mantissa,
exponent_value=exponent_value,
exponent_bits=exponent_value_bits,
floating_value=floating_value,
precision_loss=denary_value - floating_value,
)
def rename_rendered_video(scene_name: str, output_name: str) -> Path:
media_root = Path.cwd() / "media" / "videos"
matches = sorted(media_root.rglob(f"{scene_name}.mp4"), key=lambda path: path.stat().st_mtime, reverse=True)
if not matches:
raise FileNotFoundError(f"Could not find rendered video for {scene_name}")
source = matches[0]
target = source.with_name(f"{output_name}.mp4")
if target.exists():
target.unlink()
return source.replace(target)
def _slot(text: str, width: float, font_size: int = FONT_SIZE, color=WHITE) -> VGroup:
box = RoundedRectangle(corner_radius=0.08, width=width, height=ROW_HEIGHT, stroke_width=0)
box.set_fill(BLACK, opacity=0)
label = Text(text, font_size=font_size, color=color)
label.move_to(box)
return VGroup(box, label)
def _blank_slot(width: float, font_size: int = FONT_SIZE) -> VGroup:
return _slot(" ", width, font_size=font_size, color=BLACK)
def _point_marker(bits_group: VGroup, after_index: int) -> VMobject:
point = maths_text(".", font_size=BIT_FONT_SIZE + 10, color=YELLOW)
point.next_to(bits_group[after_index], RIGHT, buff=0.03)
point.align_to(bits_group[after_index], DOWN)
return point
def _standard_row(
description: str,
operator: str = "",
carry: str = "",
bits: str = "",
exponent: str = "",
point_after: int | None = None,
) -> VGroup:
description_col = _slot(description, LABEL_WIDTH)
operator_col = _slot(operator, OP_WIDTH) if operator else _blank_slot(OP_WIDTH)
carry_col = _blank_slot(CARRY_WIDTH, font_size=BIT_FONT_SIZE)
if carry:
carry_text = maths_text(carry, font_size=BIT_FONT_SIZE)
carry_text.move_to(carry_col[0])
carry_col[1] = carry_text
bits_col = _bit_group(bits)
exponent_col = _bit_group(exponent) if exponent else _blank_slot(EXP_WIDTH)
row = VGroup(description_col, operator_col, carry_col, bits_col, exponent_col).arrange(
RIGHT, buff=0.22, aligned_edge=UP
)
if point_after is not None and 0 <= point_after < len(bits_col):
row.point_marker = _point_marker(bits_col, point_after)
row.add(row.point_marker)
return row
class BinaryAdditionScene(Scene):
def __init__(
self,
a: int = 65,
b: int = 43,
bits: int = 8,
detailed_conversion: bool = False,
show_denary_headers: bool = False,
**kwargs,
):
super().__init__(**kwargs)
self.a = a
self.b = b
self.bits = bits
self.detailed_conversion = detailed_conversion
self.show_denary_headers = show_denary_headers
def _animate_denary_to_binary_breakdown(
self,
value: int,
bits: str,
bit_cells: VGroup,
color=YELLOW,
) -> None:
"""Animate a denary number sweeping across a row, revealing each bit in place."""
remaining = value
tracker = maths_text(str(value), font_size=BIT_FONT_SIZE, color=color)
tracker.move_to(bit_cells[0][0].get_center() + UP * 0.33)
self.play(FadeIn(tracker), run_time=0.2)
for col_index in range(self.bits):
target = bit_cells[col_index][0].get_center() + UP * 0.33
self.play(
tracker.animate.move_to(target),
bit_cells[col_index][1].animate.set_opacity(1.0),
run_time=0.18,
)
if bits[col_index] == "1":
column_value = 1 << (self.bits - 1 - col_index)
remaining -= column_value
updated = maths_text(str(remaining), font_size=BIT_FONT_SIZE, color=color)
updated.move_to(tracker)
self.play(Transform(tracker, updated), run_time=0.12)
self.play(FadeOut(tracker), run_time=0.2)
def construct(self):
title = Text("Binary Addition", font_size=40).to_edge(UP)
subtitle = Text(f"{self.a} + {self.b}", font_size=28, color=BLUE)
subtitle.next_to(title, DOWN, buff=0.35)
self.play(Write(title), FadeIn(subtitle, shift=UP * 0.1))
a_bin = _binary_bits(self.a, self.bits)
b_bin = _binary_bits(self.b, self.bits)
# Build the full final layout with empty answer and carry rows.
# Carry and sum rows need cell slots for each bit position, so pass spaces.
rows = VGroup(
_standard_row("", "", "", a_bin),
_standard_row("", "+", "", b_bin),
_standard_row("Carry", "", "", " " * self.bits), # carry row - empty cells to start
_standard_row("", "=", "", " " * self.bits), # sum row - empty cells to start
).arrange(DOWN, buff=ROW_GAP, aligned_edge=LEFT)
rows.next_to(subtitle, DOWN, buff=0.6).to_edge(LEFT, buff=0.65)
_align_rows(rows)
if self.show_denary_headers:
denary_headers = VGroup()
for col_index in range(self.bits):
weight = 1 << (self.bits - 1 - col_index)
header = Text(str(weight), font_size=16, color=GREY_B)
header.next_to(rows[0][3][col_index][0], UP, buff=0.08)
denary_headers.add(header)
self.play(FadeIn(denary_headers, shift=UP * 0.08), run_time=0.35)
if self.detailed_conversion:
self.add(rows)
for col_index in range(self.bits):
rows[0][3][col_index][1].set_opacity(0)
rows[1][3][col_index][1].set_opacity(0)
self.wait(0.2)
self._animate_denary_to_binary_breakdown(self.a, a_bin, rows[0][3], color=YELLOW)
self._animate_denary_to_binary_breakdown(self.b, b_bin, rows[1][3], color=ORANGE)
self.wait(0.2)
else:
# Show denary numbers morphing to binary inputs.
denary_a = maths_text(str(self.a), font_size=BIT_FONT_SIZE)
denary_b = maths_text(str(self.b), font_size=BIT_FONT_SIZE)
op_plus = Text("+", font_size=FONT_SIZE)
denary_a.align_to(rows[0][3], RIGHT).align_to(rows[0][3], UP)
denary_b.align_to(rows[1][3], RIGHT).align_to(rows[1][3], UP)
op_plus.move_to(rows[1][1])
self.play(
FadeIn(denary_a, shift=UP * 0.1),
FadeIn(op_plus, shift=UP * 0.1),
FadeIn(denary_b, shift=UP * 0.1),
)
self.wait(0.6)
# Morph denary to binary.
self.play(
Transform(denary_a, rows[0][3]),
Transform(denary_b, rows[1][3]),
run_time=1.2,
)
self.wait(0.3)
# Seamlessly replace with actual row structure.
self.remove(denary_a, denary_b, op_plus)
self.add(rows)
self.wait(0.3)
# Draw lines bracketing the work area.
x_left = rows[0][3].get_left()[0] - 0.05
x_right = rows[0][3].get_right()[0] + 0.05
top_y = rows[1].get_bottom()[1] - 0.12
bot_y = rows[2].get_bottom()[1] - 0.12
top_line = Line([x_left, top_y, 0], [x_right, top_y, 0], color=GREY_B, stroke_width=2)
bot_line = Line([x_left, bot_y, 0], [x_right, bot_y, 0], color=WHITE, stroke_width=2)
self.play(Create(top_line), Create(bot_line), run_time=0.4)
self.wait(0.2)
# Compute addition column by column, right to left.
carry = 0
carry_overflow_box = None
carry_overflow_bit = None
answer_overflow_box = None
answer_overflow_bit = None
for col_index in range(self.bits - 1, -1, -1):
incoming_carry = carry
# Extract bits from input strings.
bit_a = int(a_bin[col_index])
bit_b = int(b_bin[col_index])
# Compute sum for this column.
col_sum = bit_a + bit_b + incoming_carry
result_bit = col_sum % 2
carry_out = col_sum // 2
carry = carry_out
# Highlight the column (inputs + carry row).
col_cells = [rows[0][3][col_index], rows[1][3][col_index]]
if incoming_carry > 0 or col_index < self.bits - 1: # Include carry cell if used
col_cells.append(rows[2][3][col_index])
col_group = VGroup(*col_cells)
col_box = Rectangle(
width=rows[0][3][col_index].width + 0.14,
height=col_group.height + 0.14,
color=BLUE,
stroke_width=4,
)
col_box.move_to(col_group)
self.play(Create(col_box), run_time=0.25)
self.wait(0.15)
# Display result and carry together from the highlighted column into their cells.
result_target = rows[3][3][col_index][1]
result_cell_box = rows[3][3][col_index][0]
result_text = maths_text(str(result_bit), font_size=BIT_FONT_SIZE)
result_start = rows[0][3][col_index][0].get_center()
result_text.move_to(result_start)
reveal_anims = [result_text.animate.move_to(result_cell_box)]
staged_updates = [(result_target, result_text)]
if carry_out > 0 and col_index > 0:
carry_target = rows[2][3][col_index - 1][1]
carry_cell_box = rows[2][3][col_index - 1][0]
carry_text = maths_text("1", font_size=BIT_FONT_SIZE)
carry_start = rows[1][3][col_index][0].get_center()
carry_text.move_to(carry_start)
reveal_anims.append(carry_text.animate.move_to(carry_cell_box))
staged_updates.append((carry_target, carry_text))
# Final-column overflow uses the same reveal style/timing as normal bits.
if carry_out > 0 and col_index == 0:
carry_overflow_box = RoundedRectangle(corner_radius=0.08, width=0.44, height=0.44, stroke_width=2)
carry_overflow_box.next_to(rows[2][3][0][0], LEFT, buff=0.07)
carry_overflow_box.align_to(rows[2][3][0][0], UP)
carry_overflow_box.set_stroke(color=WHITE, opacity=0.75, width=2)
carry_overflow_box.set_fill(BLACK, opacity=0)
answer_overflow_box = RoundedRectangle(corner_radius=0.08, width=0.44, height=0.44, stroke_width=2)
answer_overflow_box.next_to(rows[3][3][0][0], LEFT, buff=0.07)
answer_overflow_box.match_x(carry_overflow_box)
answer_overflow_box.align_to(rows[3][3][0][0], UP)
answer_overflow_box.set_stroke(color=WHITE, opacity=0.75, width=2)
answer_overflow_box.set_fill(BLACK, opacity=0)
carry_overflow_bit = maths_text("1", font_size=BIT_FONT_SIZE)
answer_overflow_bit = maths_text("1", font_size=BIT_FONT_SIZE)
carry_overflow_bit.move_to(rows[1][3][0][0].get_center())
answer_overflow_bit.move_to(rows[0][3][0][0].get_center())
reveal_anims.extend(
[
FadeIn(carry_overflow_box),
FadeIn(answer_overflow_box),
carry_overflow_bit.animate.move_to(carry_overflow_box),
answer_overflow_bit.animate.move_to(answer_overflow_box),
]
)
self.add(result_text)
if carry_out > 0 and col_index > 0:
self.add(carry_text)
if carry_out > 0 and col_index == 0:
self.add(carry_overflow_bit, answer_overflow_bit)
self.play(*reveal_anims, run_time=0.2)
for target, rendered in staged_updates:
target.become(rendered)
self.remove(rendered)
self.play(FadeOut(col_box), run_time=0.15)
self.wait(0.1)
# Highlight final answer bits by turning them green.
answer_bits = VGroup(*[rows[3][3][i][1] for i in range(self.bits)])
self.play(*[bit.animate.set_color(GREEN) for bit in answer_bits], run_time=0.35)
# Color overflow artifacts red after reveal to indicate discarded overflow from the answer.
if carry_overflow_box is not None and answer_overflow_box is not None:
self.play(
carry_overflow_box.animate.set_stroke(color=RED, opacity=0.9, width=2.5),
answer_overflow_box.animate.set_stroke(color=RED, opacity=0.9, width=2.5),
carry_overflow_bit.animate.set_color(RED),
answer_overflow_bit.animate.set_color(RED),
run_time=0.2,
)
# Convert the displayed binary result back to denary without removing binary output.
displayed_result = (self.a + self.b) & ((1 << self.bits) - 1)
denary_result = Text(f"= {displayed_result}", font_size=BIT_FONT_SIZE + 2, color=GREEN)
denary_result.next_to(rows[3][3], RIGHT, buff=0.32)
denary_result.align_to(rows[3][3][0][1], DOWN)
self.play(FadeIn(denary_result, shift=RIGHT * 0.12), run_time=0.35)
self.wait(1.2)
class TwosComplementScene(Scene):
def __init__(self, value: int = 43, bits: int = 8, **kwargs):
super().__init__(**kwargs)
self.value = value
self.bits = bits
def construct(self):
title = Text("Two's Complement", font_size=40).to_edge(UP)
subtitle = Text(f"Find -{self.value} in {self.bits} bits", font_size=28, color=BLUE)
subtitle.next_to(title, DOWN, buff=0.35)
self.play(Write(title), FadeIn(subtitle, shift=UP * 0.1))
positive = _binary_bits(self.value, self.bits)
flipped = "".join("1" if bit == "0" else "0" for bit in positive)
negative = _binary_bits((1 << self.bits) - self.value, self.bits)
plus_one_bits = "0" * (self.bits - 1) + "1"
rows = VGroup(
_standard_row(f"+{self.value}", "=", "", positive),
_standard_row("Flip bits", "→", "", " " * self.bits),
_standard_row("+1", "+", "", plus_one_bits),
_standard_row("Carry", "", "", " " * self.bits),
_standard_row(f"-{self.value}", "=", "", " " * self.bits),
).arrange(DOWN, buff=ROW_GAP, aligned_edge=LEFT)
rows.next_to(subtitle, DOWN, buff=0.6).to_edge(LEFT, buff=0.65)
_align_rows(rows)
self.play(FadeIn(rows[0], shift=UP * 0.1))
# Step 1: Flip each bit one by one into the next row.
self.play(FadeIn(rows[1], shift=UP * 0.1))
x_left = rows[0][3].get_left()[0] - 0.05
x_right = rows[0][3].get_right()[0] + 0.05
flip_line_y = rows[0].get_bottom()[1] - 0.12
flip_line = Line([x_left, flip_line_y, 0], [x_right, flip_line_y, 0], color=GREY_B, stroke_width=2)
self.play(Create(flip_line), run_time=0.3)
for index in range(self.bits - 1, -1, -1):
src_box = rows[0][3][index][0]
dst_box = rows[1][3][index][0]
src_bit = rows[0][3][index][1]
dst_target = rows[1][3][index][1]
travelling = src_bit.copy().move_to(src_box)
flipped_text = maths_text(flipped[index], font_size=BIT_FONT_SIZE).move_to(dst_box)
self.add(travelling)
self.play(
travelling.animate.move_to(dst_box).stretch(0.15, 0),
run_time=0.12,
)
self.remove(travelling)
self.play(Transform(dst_target, flipped_text), run_time=0.08)
self.wait(0.15)
# Step 2: Add +1 to the flipped bits using the same column rhythm as addition.
self.play(FadeIn(rows[2], shift=UP * 0.1), FadeIn(rows[3], shift=UP * 0.1), FadeIn(rows[4], shift=UP * 0.1))
result_line_y = rows[3].get_bottom()[1] - 0.12
result_line = Line([x_left, result_line_y, 0], [x_right, result_line_y, 0], color=WHITE, stroke_width=2)
self.play(Create(result_line), run_time=0.3)
carry = 0
for col_index in range(self.bits - 1, -1, -1):
incoming_carry = carry
bit_a = int(flipped[col_index])
bit_b = int(plus_one_bits[col_index])
col_sum = bit_a + bit_b + incoming_carry
result_bit = col_sum % 2
carry_out = col_sum // 2
carry = carry_out
col_cells = [rows[1][3][col_index], rows[2][3][col_index]]
if incoming_carry > 0 or col_index < self.bits - 1:
col_cells.append(rows[3][3][col_index])
col_group = VGroup(*col_cells)
col_box = Rectangle(
width=rows[1][3][col_index].width + 0.14,
height=col_group.height + 0.14,
color=BLUE,
stroke_width=4,
)
col_box.move_to(col_group)
self.play(Create(col_box), run_time=0.2)
result_target = rows[4][3][col_index][1]
result_cell_box = rows[4][3][col_index][0]
result_text = maths_text(str(result_bit), font_size=BIT_FONT_SIZE)
result_text.move_to(result_cell_box)
reveal_anims = [Transform(result_target, result_text)]
if carry_out > 0 and col_index > 0:
carry_target = rows[3][3][col_index - 1][1]
carry_cell_box = rows[3][3][col_index - 1][0]
carry_text = maths_text("1", font_size=BIT_FONT_SIZE)
carry_text.move_to(carry_cell_box)
reveal_anims.append(Transform(carry_target, carry_text))
self.play(*reveal_anims, run_time=0.2)
self.play(FadeOut(col_box), run_time=0.12)
result_bits = VGroup(*[rows[4][3][i][1] for i in range(self.bits)])
self.play(*[bit.animate.set_color(GREEN) for bit in result_bits], run_time=0.3)
self.wait(1.0)
class FixedToFloatingScene(Scene):
def __init__(
self,
denary_value: float = 12.25,
integer_bits: int = 4,
fraction_bits: int = 4,
mantissa_bits: int = 8,
exponent: int | None = None,
exponent_bits: int = 4,
detailed_conversion: bool = False,
show_headers: bool = False,
**kwargs,
):
super().__init__(**kwargs)
self.denary_value = denary_value
self.integer_bits = integer_bits
self.fraction_bits = fraction_bits
self.mantissa_bits = mantissa_bits
self.exponent = exponent
self.exponent_bits = exponent_bits
self.detailed_conversion = detailed_conversion
self.show_headers = show_headers
def _fixed_from_denary(self) -> tuple[str, str]:
return _fixed_from_denary_value(self.denary_value, self.integer_bits, self.fraction_bits)
def _animate_denary_to_fixed_breakdown(
self,
value: float,
bits: str,
bit_cells: VGroup,
point_after: int,
color=YELLOW,
) -> None:
"""Animate denary to fixed-binary conversion by sweeping across bit cells."""
remaining = value
tracker = maths_text(f"{remaining:g}", font_size=BIT_FONT_SIZE, color=color)
tracker.move_to(bit_cells[0][0].get_center() + UP * 0.33)
self.play(FadeIn(tracker), run_time=0.2)
for col_index in range(len(bits)):
target = bit_cells[col_index][0].get_center() + UP * 0.33
self.play(
tracker.animate.move_to(target),
bit_cells[col_index][1].animate.set_opacity(1.0),
run_time=0.18,
)
if bits[col_index] == "1":
power = point_after - col_index
column_value = 2**power
remaining -= column_value
updated = maths_text(f"{remaining:g}", font_size=BIT_FONT_SIZE, color=color)
updated.move_to(tracker)
self.play(Transform(tracker, updated), run_time=0.12)
self.play(FadeOut(tracker), run_time=0.2)
def construct(self):
title = Text("Fixed to Floating Point", font_size=40).to_edge(UP)
subtitle = Text(f"{self.denary_value:g}", font_size=28, color=BLUE)
subtitle.next_to(title, DOWN, buff=0.35)
self.play(Write(title), FadeIn(subtitle, shift=UP * 0.1))
components = _floating_point_components(
self.denary_value,
self.integer_bits,
self.fraction_bits,
self.mantissa_bits,
self.exponent_bits,
self.exponent,
)
fixed_value = components.fixed_value
fixed_bits = components.fixed_bits
fixed_point_after = self.integer_bits - 1
mantissa_bits = components.mantissa_bits
exponent_value = components.exponent_value
initial_point_after = min(exponent_value, self.mantissa_bits - 1)
shifts_needed = initial_point_after
exponent_bits = components.exponent_bits
fixed_represented_value = components.fixed_value_numeric
floating_represented_value = components.floating_value
precision_loss = components.precision_loss
rows = VGroup(
_standard_row("Fixed", "=", "", " " * len(fixed_bits), point_after=fixed_point_after),
_standard_row("Floating point", "=", "", " " * len(mantissa_bits), " " * self.exponent_bits, point_after=initial_point_after),
).arrange(DOWN, buff=ROW_GAP, aligned_edge=LEFT)
rows.next_to(subtitle, DOWN, buff=0.6).to_edge(LEFT, buff=0.65)
_align_rows(rows)
# Prepare fixed-row bit glyphs but keep them hidden until conversion animation reveals them.
for col_index, bit in enumerate(fixed_bits):
bit_text = maths_text(bit, font_size=BIT_FONT_SIZE)
bit_text.move_to(rows[0][3][col_index][0])
rows[0][3][col_index][1].become(bit_text)
rows[0][3][col_index][1].set_opacity(0)
if self.show_headers:
denary_headers = VGroup()
for col_index in range(len(fixed_bits)):
power = fixed_point_after - col_index
if power >= 0:
label = str(1 << power)
else:
label = f"1/{1 << (-power)}"
header = Text(label, font_size=16, color=GREY_B)
header.next_to(rows[0][3][col_index][0], UP, buff=0.08)
denary_headers.add(header)
self.play(FadeIn(denary_headers, shift=UP * 0.08), run_time=0.35)
step_1 = Text("Step 1: Convert denary to fixed binary", font_size=20, color=YELLOW)
step_1.next_to(rows, LEFT, buff=0.65).align_to(rows[0], UP)
self.play(FadeIn(step_1, shift=RIGHT * 0.1), run_time=0.25)
self.play(FadeIn(rows[0], shift=UP * 0.1), FadeIn(rows[1], shift=UP * 0.1))
if self.detailed_conversion:
self._animate_denary_to_fixed_breakdown(
self.denary_value,
fixed_bits,
rows[0][3],
fixed_point_after,
color=YELLOW,
)
else:
denary_number = maths_text(f"{self.denary_value:g}", font_size=BIT_FONT_SIZE, color=YELLOW)
denary_number.move_to(rows[0][3])
target_bits = rows[0][3].copy()
for col_index, bit in enumerate(fixed_bits):
bit_text = maths_text(bit, font_size=BIT_FONT_SIZE)
bit_text.move_to(target_bits[col_index][0])
target_bits[col_index][1].become(bit_text)
target_bits[col_index][1].set_opacity(1.0)
self.play(FadeIn(denary_number, shift=UP * 0.1), run_time=0.25)
self.play(Transform(denary_number, target_bits), run_time=1.0)
for col_index in range(len(fixed_bits)):
rows[0][3][col_index][1].set_opacity(1.0)
self.remove(denary_number)
step_2 = Text("Step 2: Shift point left to normalise", font_size=20, color=YELLOW)
step_2.next_to(rows, LEFT, buff=0.65).align_to(rows[1], UP)
self.play(Transform(step_1, step_2), run_time=0.3)
move_count = 0
move_counter = Text("Moves: 0", font_size=19, color=YELLOW)
move_counter.next_to(step_1, DOWN, buff=0.12).align_to(step_1, LEFT)
display_point_after = initial_point_after
point_display = Text(
f"{mantissa_bits[:display_point_after+1]}.{mantissa_bits[display_point_after+1:]}",
font_size=18,
color=YELLOW,
)
point_display.next_to(move_counter, DOWN, buff=0.08).align_to(move_counter, LEFT)
self.play(FadeIn(move_counter, shift=UP * 0.05), FadeIn(point_display, shift=UP * 0.05), run_time=0.2)
top_line_y = rows[0].get_bottom()[1] - 0.12
x_left = rows[0][3].get_left()[0] - 0.05
x_right = rows[0][3].get_right()[0] + 0.05
top_line = Line([x_left, top_line_y, 0], [x_right, top_line_y, 0], color=GREY_B, stroke_width=2)
self.play(Create(top_line), run_time=0.25)
first_one_index = fixed_bits.find("1")
sign_target = rows[1][3][0][1]
sign_text = maths_text(mantissa_bits[0], font_size=BIT_FONT_SIZE).move_to(rows[1][3][0][0])
self.play(Transform(sign_target, sign_text), run_time=0.08)
for target_index in range(1, len(mantissa_bits)):
source_index = first_one_index + target_index - 1 if first_one_index != -1 else -1
target = rows[1][3][target_index][1]
target_text = maths_text(mantissa_bits[target_index], font_size=BIT_FONT_SIZE).move_to(rows[1][3][target_index][0])
if 0 <= source_index < len(fixed_bits):
travelling_cell = rows[0][3][source_index].copy()
travelling_cell.move_to(rows[0][3][source_index][0])
self.add(travelling_cell)
self.play(travelling_cell.animate.move_to(rows[1][3][target_index][0]), run_time=0.12)
self.remove(travelling_cell)
self.play(Transform(target, target_text), run_time=0.06)
point_marker = rows[1].point_marker
for step in range(shifts_needed):
src_index = initial_point_after - step
dst_index = src_index - 1
shift_box = SurroundingRectangle(VGroup(rows[1][3][dst_index], rows[1][3][src_index]), color=BLUE, buff=0.03)
self.play(Create(shift_box), run_time=0.14)
target_pos = point_marker.copy()
target_pos.next_to(rows[1][3][dst_index], RIGHT, buff=0.03)
target_pos.align_to(rows[1][3][dst_index], DOWN)
move_count += 1
display_point_after = max(0, display_point_after - 1)
updated_counter = Text(f"Moves: {move_count}", font_size=19, color=YELLOW)
updated_counter.move_to(move_counter)
updated_point_display = Text(
f"{mantissa_bits[:display_point_after+1]}.{mantissa_bits[display_point_after+1:]}",
font_size=18,
color=YELLOW,
)
updated_point_display.move_to(point_display)
self.play(
point_marker.animate.move_to(target_pos),
Transform(move_counter, updated_counter),
Transform(point_display, updated_point_display),
run_time=0.16,
)
self.play(FadeOut(shift_box), run_time=0.08)
step_3 = Text("Step 3: Convert move count to exponent", font_size=20, color=YELLOW)
step_3.next_to(rows, LEFT, buff=0.65).align_to(rows[1], UP)
self.play(Transform(step_1, step_3), run_time=0.25)
decimal_to_binary = Text(f"{move_count} -> {exponent_bits}", font_size=19, color=YELLOW)
decimal_to_binary.next_to(rows[1][4], UP, buff=0.1)
self.play(Transform(move_counter, decimal_to_binary), FadeOut(point_display), run_time=0.25)
mantissa_label = Text("Mantissa", font_size=18, color=GREY_B)
exponent_label = Text("Exponent", font_size=18, color=GREY_B)
mantissa_label.next_to(rows[1][3], DOWN, buff=0.08)
exponent_label.next_to(rows[1][4], DOWN, buff=0.08)
self.play(FadeIn(mantissa_label, shift=UP * 0.05), FadeIn(exponent_label, shift=UP * 0.05), run_time=0.2)
# Reveal exponent bits in-place after normalization.
exponent_cells = rows[1][4]
exp_reveals = []
for idx, bit in enumerate(exponent_bits):
target = exponent_cells[idx][1]
target_text = maths_text(bit, font_size=BIT_FONT_SIZE).move_to(exponent_cells[idx][0])
exp_reveals.append(Transform(target, target_text))
self.play(*exp_reveals, run_time=0.35)
self.play(FadeOut(move_counter), run_time=0.2)
mantissa_bit_glyphs = VGroup(*[rows[1][3][i][1] for i in range(len(mantissa_bits))])
self.play(*[bit.animate.set_color(GREEN) for bit in mantissa_bit_glyphs], run_time=0.25)
step_4 = Text("Step 4: Convert floating point back to denary", font_size=20, color=YELLOW)
step_4.next_to(rows, LEFT, buff=0.65).align_to(rows[1], UP)
self.play(Transform(step_1, step_4), run_time=0.25)
mantissa_display = f"{mantissa_bits[0]}.{mantissa_bits[1:]}"
floating_text = Text(
f"Floating: {mantissa_display} {exponent_bits} (exp = {exponent_value})",
font_size=22,
color=BLUE,
)
floating_text.next_to(rows, DOWN, buff=0.55).align_to(rows, LEFT)
fixed_text = Text(
f"Fixed value: {fixed_value} = {fixed_represented_value:g}",
font_size=22,
color=GREY_B,
)
fixed_text.next_to(floating_text, DOWN, buff=0.15).align_to(floating_text, LEFT)
round_trip_text = Text(
f"Floating round trip: {self.denary_value:g} -> {floating_represented_value:g}",
font_size=24,
color=GREEN,
)
round_trip_text.next_to(fixed_text, DOWN, buff=0.15).align_to(floating_text, LEFT)
loss_text = Text(
f"Precision loss: {abs(precision_loss):g}",
font_size=22,
color=RED if abs(precision_loss) > 0 else GREEN,
)
loss_text.next_to(round_trip_text, DOWN, buff=0.15).align_to(round_trip_text, LEFT)
self.play(FadeIn(floating_text, shift=UP * 0.06), run_time=0.25)
self.play(FadeIn(fixed_text, shift=UP * 0.06), run_time=0.25)
self.play(FadeIn(round_trip_text, shift=UP * 0.06), run_time=0.25)
self.play(FadeIn(loss_text, shift=UP * 0.06), run_time=0.25)
self.play(FadeOut(step_1), run_time=0.2)
self.wait(1.0)