Skip to content

Instantly share code, notes, and snippets.

@nesteruk
Created November 25, 2021 10:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nesteruk/b3231b33649593ab8b6bec72da017acf to your computer and use it in GitHub Desktop.
Save nesteruk/b3231b33649593ab8b6bec72da017acf to your computer and use it in GitHub Desktop.
#%%
from math import *
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 10, 1001)
f = lambda z: z * sin(z)
y = np.sin(x) * x
#plt.plot(x, y)
x0, y0 = x[0], y[0]
circle_radius = req_dist = 0.5
#%%
def func(est):
y = f(est)
dist = sqrt((x0-est)**2 + (y0-y)**2)
return dist - req_dist
def bisection(cf, a, b, tol, max_iter):
sign = lambda z: copysign(1, z)
n = 1
while n <= max_iter:
c = (a+b)/2
if abs(cf(c)) < tol:
return c
n += 1
if sign(cf(c)) == sign(cf(a)):
a = c
else:
b = c
return None
guess = bisection(func, x[0], x[-1], 1e-3, 1000)
fig, axes = plt.subplots()
axes.set_aspect('equal', adjustable='datalim')
circle = plt.Circle((guess, f(guess)), circle_radius, fill=None)
axes.add_patch(circle)
req_dist *= 2
for i in range(35):
x0, y0 = guess, f(guess)
guess = bisection(func, x0, x[-1], 1e-3, 1000)
circle = plt.Circle((guess, f(guess)), circle_radius, fill=None)
axes.add_patch(circle)
plt.plot(x, y)
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment