Skip to content

Instantly share code, notes, and snippets.

@MathiasYde
Created February 8, 2022 15:21
Show Gist options
  • Save MathiasYde/0face70dbac582a7da19a48c32082ac6 to your computer and use it in GitHub Desktop.
Save MathiasYde/0face70dbac582a7da19a48c32082ac6 to your computer and use it in GitHub Desktop.
import numpy as np
from manimlib import *
import math
class NewtonRaphsonExample(Scene):
def newton_raphson_solve(self, x):
result = x - self.f(x)/self.df(x)
# It is possible that the result will be infinite,
# In that case, we just return a large number.
# In reality, this is terrible.
# But this is just for a visualization, so it's fine.
if np.isinf(result):
return 10000
return result
def construct(self):
# Wait four seconds to allow time to fullscreen application
self.wait(4)
# Define the function and its derivative version
self.f = lambda x: 1.2*x-2.8+math.sin(x)
self.df = lambda x: math.cos(x)+1.2
x_range = (-1, 10)
y_range = (-1, 5)
grid = NumberPlane(
x_range, y_range,
background_line_style={"stroke_opacity": 0.2}
)
self.play(ShowCreation(grid))
self.wait()
graph = grid.get_graph(self.f, color=BLUE)
self.play(ShowCreation(graph))
dot = Dot(color=GREEN)
xdot = Dot(color=RED)
# Initial guess for x in f(x)=0
x_tracker = ValueTracker(6)
f_always(
dot.move_to,
lambda: grid.i2gp(x_tracker.get_value(), graph)
)
f_always(
xdot.move_to,
lambda: grid.coords_to_point(
self.newton_raphson_solve(x_tracker.get_value()),
0
)
)
tangent = TangentLine(
graph,
alpha=0.5, # Why do I have to specify the angle?
length=100
)
# This feels like a hack.
# I should just be able to say
# "Hey, draw a line that's tangent to this
# function given this point."
# Important note, rotate, then translate.
# This avoids jittering.
f_always(
tangent.set_angle,
lambda: grid.angle_of_tangent(x_tracker.get_value(), graph)
)
f_always(
tangent.move_to,
lambda: grid.i2gp(x_tracker.get_value(), graph)
)
self.play(ShowCreation(tangent), FadeIn(dot), FadeIn(xdot))
self.wait(4)
for i in range(4):
# Add a line where the tangent line is
self.add(DashedLine(
dot,
xdot,
color=GREY
))
# Calculate x_n+1 and play a nice little animation
self.play(
x_tracker.animate.set_value(
self.newton_raphson_solve(
x_tracker.get_value()
)
),
run_time=1
)
# Add a line from x_n to (x_n, f(x_n))
self.add(DashedLine(
dot,
Dot(point=grid.c2p(
x_tracker.get_value(),
0,
0
)),
color=GREY
))
self.wait()
self.wait()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment