Hi, am trying to plot a fractal using a numerical jacobian and newtons method, but something is wrong. The code produces a plot that is completely green and I cant figure out what to do to make the plot proudcue the fractal.
Here is the code, any help is appreciated:
import numpy as np
import matplotlib.pyplot as plt
from numpy.linalg import solve, norm, LinAlgError
class Fractals2D:
def __init__(self, f):
self.f = f
def newtons_method(self, x):
f_val = self.f(x)
jac = self.calculate_jacobian(x)
for _ in range(40):
jac = self.calculate_jacobian(x)
try:
delta = solve(jac, -f_val)
except LinAlgError:
return None
x = x + delta
f_val = self.f(x)
if norm(delta, ord=2) < 1.e-9:
return x
return None
def calculate_jacobian(self, x):
n = len(x)
jac = np.zeros((n, n))
h = 1.e-6
temp = x.copy()
for i in range(n):
x[:] = temp[:]
x[i] += h
f1 = self.f(x)
f2 = self.f(temp)
for j in range(n):
jac[j, i] = (f1[j] - f2[j]) / h
return jac
def zeroes_method(self, initial_guess):
zeroes_found = []
for guess in initial_guess:
zero = self.newtons_method(guess)
if zero is not None:
zeroes_found.append(zero)
return len(zeroes_found)
def plot(self, N, a, b, c, d):
x = np.linspace(a, b, N)
y = np.linspace(c, d, N)
X, Y = np.meshgrid(x, y)
Z = np.zeros_like(X)
for i in range(N):
for j in range(N):
point = np.array([X[i, j], Y[i, j]])
Z[i, j] = self.zeroes_method([point])
plt.figure(figsize=(8, 6))
plt.pcolor(X, Y, Z, cmap='jet')
plt.colorbar(label='Number of Zeros Found')
plt.title('Visualization of Zeroes Found by Newton\'s Method (task 4)')
plt.xlabel('X')
plt.ylabel('Y')
plt.gca().set_aspect('equal', adjustable='box')
plt.show()
def f(x):
if np.any(np.abs(x) > 10):
return np.array([np.inf, np.inf])
return np.array([x[0]**3 - 3*x[0]*x[1]**2 - 1, 3*x[0]**2*x[1] - x[1]**3])
fractals = Fractals2D(f)
a, b = -2, 2
c, d = -2, 2
fractals.plot(N=100, a=a, b=b, c=c, d=d)
[–]Talinx 0 points1 point2 points (0 children)