Beispiel #1
0
    def construct(self):
        code_scale = 0.75
        ss_code = CodeBlock(
            'Java',
            r"""
            public static double StrangeSqrt(double a) { 
                if (a < 0) { 
                    double b = StrangeSqrt(a * -1);
                    return b;
                } 
                return Math.sqrt(a);
            }
            """,
            code_scale=code_scale,
        )

        t1 = TextMobject(
            'Consider this somewhat strange square root function:')
        t1.next_to(ss_code, UP, buff=LARGE_BUFF)
        self.play(
            FadeIn(t1),
            ShowCreation(ss_code),
        )
        self.wait(duration=2.5)

        t2 = TextMobject(
            'It has a recursive call, meaning \\textit{it calls itself.}')
        t2.next_to(ss_code, DOWN, buff=LARGE_BUFF)
        # 012345 6 7 8901234567890 1 2345
        # double b = StrangeSqrt(a * -1);
        rl = ss_code.get_code().get_lines(3)
        rc_highlight = SurroundingRectangle(rl[8:-1])
        self.play(
            FadeIn(t2),
            FadeIn(rc_highlight),
        )
        self.wait(duration=3)
        self.play(
            FadeOut(t2),
            FadeOut(rc_highlight),
        )

        # Run with a positive input
        main_code = CodeBlock(
            'Java',
            r"""
            public static void main(String[] args) {
                double n = StrangeSqrt(4);
            }
            """,
            line_offset=7,
            code_scale=code_scale - 0.1,
        )
        frame_width = 3.5
        main_frame = StackFrame(main_code,
                                'main()',
                                9, ['n'],
                                width=frame_width)
        main_code.highlight_lines(9)
        VGroup(main_code, main_frame).arrange(RIGHT,
                                              buff=LARGE_BUFF).to_edge(DOWN)
        t3 = TextMobject("Let's see what it does with a positive input...")\
            .next_to(ss_code, DOWN, buff=LARGE_BUFF)
        self.play(
            FadeOut(t1),
            MaintainPositionRelativeTo(t1, ss_code),
            ss_code.to_edge,
            UP,
            FadeIn(t3),
            MaintainPositionRelativeTo(t3, ss_code),
        )
        self.wait()
        self.play(
            FadeInFromDown(main_frame),
            FadeInFromDown(main_code),
        )
        self.wait()

        ss_frame = StackFrame(ss_code,
                              'StrangeSqrt(4)',
                              1, ['a', 'b'],
                              width=frame_width)
        ss_frame.next_to(main_frame, UP, buff=SMALL_BUFF)

        xi = main_code.pre_call(ss_code, 1)
        self.play(
            *main_code.get_control_transfer_counterclockwise(xi),
            FadeInFrom(ss_frame, UP),
            FadeOut(t3),
        )
        ss_code.post_control_transfer(xi, self)
        self.wait()

        self.play(
            ss_code.highlight_lines,
            2,
            ss_frame.set_line,
            2,
            ss_frame.update_slot,
            'a',
            4,
        )
        self.wait()

        self.play(
            ss_code.highlight_lines,
            6,
            ss_frame.set_line,
            6,
        )
        self.wait()

        xi = ss_code.pre_return(main_code, 9)
        self.play(
            *ss_code.get_control_transfer_clockwise(xi),
            Uncreate(ss_frame),
        )
        main_code.post_control_transfer(xi, self)
        self.wait()

        t1 = TextMobject('That seems pretty normal...').next_to(
            ss_code, DOWN, buff=LARGE_BUFF)
        self.play(
            main_code.highlight_lines,
            10,
            main_frame.set_line,
            10,
            main_frame.update_slot,
            'n',
            2,
            FadeIn(t1),
        )
        self.wait(duration=2)

        t2 = TextMobject("Let's try it with a negative input...")\
            .next_to(ss_code, DOWN, buff=LARGE_BUFF)
        self.play(
            FadeOutAndShiftDown(main_code),
            FadeOutAndShiftDown(main_frame),
            FadeOut(t1),
            FadeIn(t2),
        )

        # Run with a negative input and see the recursion
        main_code = CodeBlock(
            'Java',
            r"""
            public static void main(String[] args) {
                double n = StrangeSqrt(-4);
            }
            """,
            line_offset=7,
            code_scale=code_scale - 0.1,
        )
        main_frame = StackFrame(main_code,
                                'main()',
                                9, ['n'],
                                width=frame_width)
        main_code.highlight_lines(9)
        VGroup(main_code, main_frame).arrange(RIGHT,
                                              buff=LARGE_BUFF).to_edge(DOWN)

        self.play(
            FadeInFromDown(main_frame),
            FadeInFromDown(main_code),
        )
        self.wait()

        ss_frame = StackFrame(ss_code,
                              'StrangeSqrt(-4)',
                              1, ['a', 'b'],
                              width=frame_width)
        ss_frame.next_to(main_frame, UP, buff=SMALL_BUFF)
        xi = main_code.pre_call(ss_code, 1)
        self.play(
            *main_code.get_control_transfer_counterclockwise(xi),
            FadeInFrom(ss_frame, UP),
            FadeOut(t2),
        )
        ss_code.post_control_transfer(xi, self)
        self.wait()

        self.play(
            ss_code.highlight_lines,
            2,
            ss_frame.set_line,
            2,
            ss_frame.update_slot,
            'a',
            -4,
        )
        self.wait()

        self.play(
            ss_code.highlight_lines,
            3,
            ss_frame.set_line,
            3,
        )
        self.wait()

        self.play(Indicate(rl[8:-1]), )

        ss2_frame = StackFrame(ss_code,
                               'StrangeSqrt(4)',
                               1, ['a', 'b'],
                               width=frame_width)
        ss2_frame.next_to(ss_frame, UP, buff=SMALL_BUFF)

        r1_call_site_rect = ss_code.get_current_highlight().copy().set_color(
            WHITE)
        self.play(
            FadeInFrom(ss2_frame, UP),
            ss_code.highlight_lines,
            1,
            FadeIn(r1_call_site_rect),
        )
        self.wait()

        stack = VGroup(main_frame, ss_frame, ss2_frame)
        t1 = TextMobject('Same function, but with\\\\a new frame on the stack')\
            .next_to(stack, LEFT, buff=LARGE_BUFF).shift(UP * 0.5)
        a = Arrow(t1.get_right(), ss2_frame.get_left(), stroke_width=3)
        self.play(
            FadeIn(t1),
            GrowArrow(a),
        )
        self.wait(duration=2)

        # Now we have a positive input again
        self.play(
            ss_code.highlight_lines,
            2,
            ss2_frame.set_line,
            2,
            ss2_frame.update_slot,
            'a',
            4,
        )
        self.wait()

        self.play(
            ss_code.highlight_lines,
            6,
            ss2_frame.set_line,
            6,
            FadeOut(t1),
            FadeOut(a),
        )
        self.wait()

        t1 = TextMobject('The stack tells us where to return,\\\\and with which values')\
            .next_to(stack, LEFT, buff=LARGE_BUFF).shift(UP * 0.5)
        a = Arrow(t1.get_right(), ss_frame.get_left(), stroke_width=3)
        self.play(
            FadeIn(t1),
            GrowArrow(a),
        )
        self.wait(duration=2)

        # Return back to line 3...
        self.play(
            FadeOut(r1_call_site_rect),
            Uncreate(ss2_frame),
            ss_code.highlight_lines,
            3,
            ss_frame.set_line,
            3,
        )
        self.wait()

        self.play(
            ss_code.highlight_lines,
            4,
            ss_frame.set_line,
            4,
            ss_frame.update_slot,
            'b',
            2,
            FadeOut(t1),
            FadeOut(a),
        )
        self.wait()

        xi = ss_code.pre_return(main_code, 9)
        self.play(
            *ss_code.get_control_transfer_clockwise(xi),
            Uncreate(ss_frame),
        )
        main_code.post_control_transfer(xi, self)
        self.wait()
        self.play(
            main_code.highlight_lines,
            10,
            main_frame.set_line,
            10,
            main_frame.update_slot,
            'n',
            2,
        )
        self.wait()

        t1 = TextMobject(
            'Thinking about the call stack can help you keep track of\\\\'
            'what a recursive function is doing at any given moment.').next_to(
                ss_code, DOWN, buff=LARGE_BUFF)
        self.play(
            FadeOutAndShiftDown(main_code),
            FadeOutAndShiftDown(main_frame),
            FadeIn(t1),
        )
        self.wait(duration=3)
        t2 = TextMobject('Try writing down part of the stack as you go.')\
            .next_to(t2, DOWN, buff=LARGE_BUFF)
        self.play(FadeInFromDown(t2))
        self.wait(duration=2)

        self.play(
            FadeOut(t1),
            FadeOut(t2),
        )
        self.wait()
Beispiel #2
0
    def construct(self):
        # - Now, let's change this a bit and break it!
        # - Now modify it (a <= 0) and call it with foo(0).
        # - switch it out for the broken one, and highlight and note the change.
        code_scale = 0.75
        ss_good_code = CodeBlock(
            'Java',
            r"""
            public static double StrangeSqrt(double a) { 
                if (a < 0) { 
                    double b = StrangeSqrt(a * -1);
                    return b;
                } 
                return Math.sqrt(a);
            }
            """,
            code_scale=code_scale,
        )
        ss_good_code.to_edge(UP)
        self.add(ss_good_code)

        t1 = TextMobject(
            "Let's break this code in a very small way and\\\\see what happens..."
        )
        t1.next_to(ss_good_code, DOWN, buff=LARGE_BUFF)
        self.play(FadeIn(t1))
        self.wait()

        gl2 = ss_good_code.get_code().get_lines(2)
        ghr = SurroundingRectangle(gl2[3:6])
        self.play(ShowCreation(ghr))
        self.wait()

        ss_bad_code = CodeBlock(
            'Java',
            r"""
            public static double StrangeSqrt(double a) { 
                if (a <= 0) { 
                    double b = StrangeSqrt(a * -1);
                    return b;
                } 
                return Math.sqrt(a);
            }
            """,
            code_scale=code_scale,
        )
        ss_bad_code.to_edge(UP)
        bl2 = ss_bad_code.get_code().get_lines(2)
        bhr = SurroundingRectangle(bl2[3:7])
        self.play(
            ReplacementTransform(ss_good_code, ss_bad_code),
            ReplacementTransform(ghr, bhr),
        )
        self.wait()

        t2 = TextMobject(
            "This small change will have a big effect on one case: 0\\\\"
            "Let's run it and see.").next_to(ss_bad_code,
                                             DOWN,
                                             buff=LARGE_BUFF)
        self.play(
            FadeOut(t1),
            FadeIn(t2),
        )
        self.wait(duration=3)

        self.play(
            FadeOut(t2),
            FadeOut(bhr),
        )
        self.wait()

        # - Start stepping through this and see the stack start to grow forever.
        main_code = CodeBlock(
            'Java',
            r"""
            public static void main(String[] args) {
                double n = StrangeSqrt(0);
            }
            """,
            line_offset=7,
            code_scale=code_scale - 0.1,
        )
        frame_width = 3.5
        main_frame = StackFrame(main_code,
                                'main()',
                                9, ['n'],
                                width=frame_width)
        main_code.highlight_lines(9)
        VGroup(main_code, main_frame).arrange(RIGHT,
                                              buff=LARGE_BUFF).to_edge(DOWN)
        self.play(
            FadeInFromDown(main_frame),
            FadeInFromDown(main_code),
        )
        self.wait()

        ss_frame = StackFrame(ss_bad_code,
                              'StrangeSqrt(0)',
                              1, ['a', 'b'],
                              width=frame_width)
        ss_frame.next_to(main_frame, UP, buff=SMALL_BUFF)

        xi = main_code.pre_call(ss_bad_code, 1)
        self.play(
            *main_code.get_control_transfer_counterclockwise(xi),
            FadeInFrom(ss_frame, UP),
        )
        ss_bad_code.post_control_transfer(xi, self)
        self.wait()

        self.play(ss_bad_code.highlight_lines, 2, ss_frame.set_line, 2,
                  ss_frame.update_slot, 'a', 0)
        self.wait()

        self.play(ss_bad_code.highlight_lines, 3, ss_frame.set_line, 3)
        self.wait()

        def call_ss_again(stack_group, previous_frame, extras=None):
            wait_each_step = len(stack_group) < 3
            runtime = 1.0 if len(stack_group) < 2 else 0.5 if len(
                stack_group) < 6 else 0.20
            extra_anims = []
            if len(stack_group) > 2:
                extra_anims.append(
                    ApplyMethod(
                        stack_group.shift,
                        DOWN * previous_frame.get_height() +
                        DOWN * SMALL_BUFF))
            if extras:
                extra_anims.extend(extras)

            f = StackFrame(ss_bad_code,
                           'StrangeSqrt(0)',
                           1, ['a', 'b'],
                           width=frame_width)
            f.next_to(previous_frame, UP, buff=SMALL_BUFF)
            self.play(*extra_anims,
                      ss_bad_code.highlight_lines,
                      1,
                      f.set_line,
                      1,
                      FadeIn(f),
                      MaintainPositionRelativeTo(f, previous_frame),
                      run_time=runtime)
            if wait_each_step:
                self.wait()

            self.play(ss_bad_code.highlight_lines,
                      2,
                      f.set_line,
                      2,
                      f.update_slot,
                      'a',
                      0,
                      run_time=runtime)
            if wait_each_step:
                self.wait()

            self.play(ss_bad_code.highlight_lines,
                      3,
                      f.set_line,
                      3,
                      run_time=runtime)
            if wait_each_step:
                self.wait()
            stack_group.add(f)
            return f

        sg = VGroup(main_frame, ss_frame)
        curr_ss_frame = ss_frame
        for i in range(3):
            curr_ss_frame = call_ss_again(sg, curr_ss_frame)

        # - When will this program end? Never?
        t1 = TextMobject("Hrm... when is this going to end??").next_to(
            main_code, UP, buff=LARGE_BUFF)
        extra_text = [FadeIn(t1)]
        for i in range(4):
            curr_ss_frame = call_ss_again(sg, curr_ss_frame, extra_text)
            extra_text = None

        t2 = TextMobject("Never?").next_to(main_code, UP, buff=LARGE_BUFF)
        extra_text = [FadeOut(t1), FadeIn(t2)]
        for i in range(4):
            curr_ss_frame = call_ss_again(sg, curr_ss_frame, extra_text)
            extra_text = None

        sg.save_state()
        t3 = TextMobject("The stack is getting quite deep!").next_to(
            main_code, UP, buff=LARGE_BUFF)
        self.play(sg.scale, 0.20, {'about_edge': TOP}, FadeOut(t2), FadeIn(t3))
        self.wait(duration=2)
        self.play(sg.restore)

        extra_text = [FadeOut(t3)]
        for i in range(4):
            curr_ss_frame = call_ss_again(sg, curr_ss_frame, extra_text)
            extra_text = None

        # - Well, the stack is finite, so eventually you get a SO.
        #   Use the Java SO exception and show it hit and stop.
        so_frame = StackFrame(ss_bad_code,
                              'StrangeSqrt(0)',
                              1, ['a', 'b'],
                              width=frame_width)
        so_frame.slots().set_color(ORANGE)
        so_frame.header_line().set_color(ORANGE)
        so_frame.background_rect().set_fill(color=[BLACK, RED])
        so_frame.next_to(curr_ss_frame, UP, buff=SMALL_BUFF)
        so_exception = TextMobject(
            '\\texttt{Exception in thread "main"\\\\java.lang.StackOverflowError}',
        ).set_color(YELLOW).scale(0.75).next_to(main_code, UP, buff=LARGE_BUFF)
        self.play(sg.shift,
                  DOWN * so_frame.get_height() + DOWN * SMALL_BUFF,
                  ss_bad_code.get_current_highlight().set_color, ORANGE,
                  FadeIn(so_frame),
                  MaintainPositionRelativeTo(so_frame, curr_ss_frame),
                  Write(so_exception))
        sg.add(so_frame)
        self.wait(duration=2)

        ss_bad_code.generate_target()
        so_exception.generate_target()
        ss_bad_code.target.scale(0.75)
        g = VGroup(so_exception.target,
                   ss_bad_code.target).arrange(RIGHT, buff=LARGE_BUFF)
        g.to_edge(UP)
        sg.generate_target()
        sg.target.scale(0.15).next_to(g, DOWN).to_edge(RIGHT)
        t1 = TextMobject(
            "Space for the call stack is limited,\\\\so we can't make recursive calls forever!"
        )
        self.play(
            *[MoveToTarget(t) for t in [so_exception, ss_bad_code, sg]],
            FadeOutAndShiftDown(main_code),
            FadeInFromDown(t1),
        )
        self.wait(duration=2)

        t2 = TextMobject(
            "This program made {\\raise.17ex\\hbox{$\\scriptstyle\\sim$}}15,000 calls before crashing."
        )
        t4 = TextMobject(
            "\\textit{Java SE 13.0.1 on macOS Catalina 10.15.4}").scale(0.5)
        t2.next_to(t1, DOWN, buff=MED_LARGE_BUFF)
        t4.to_edge(DL)
        self.play(
            FadeIn(t2),
            FadeInFromDown(t4),
        )
        self.wait(duration=4)

        t5 = TextMobject('\\textit{Most common mistake with recursion.}')
        t6 = TextMobject("You'll see this a lot. Everyone does!")
        t6.next_to(t5, DOWN, buff=LARGE_BUFF)
        self.play(
            *[FadeOut(t) for t in [t1, t2, t4]],
            *[FadeIn(t) for t in [t5, t6]],
        )
        self.wait(duration=3)

        # Transition
        t1 = TextMobject(
            "Alright, let's look at a more interesting function...")
        self.play(
            *[FadeOut(o) for o in self.mobjects],
            FadeIn(t1),
        )
        self.wait()

        self.play(FadeOut(t1))
        self.wait()