gpt-4-0314· openai
Suzhen/CodeChat
напиши код на языке python, которая найдет первые 3 корня уравнения tan(ax)=sqrt(bx),…
- User
напиши код на языке python, которая найдет первые 3 корня уравнения tan(ax)=sqrt(bx), где a=2 b=1, с точностью 10^(-6) методами Ньютона, дихотомии и парабол
- Assistant
Для решения данной задачи, сначала импортируем необходимые библиотеки и определим уравнение и его производную. Затем напишем функции для методов Ньютона, дихотомии и парабол.
import math import numpy as np eps = 1e-6 a = 2 b = 1 def f(x): return math.tan(a * x) - math.sqrt(b * x) def df(x): return a * (1 / (math.cos(a * x)) ** 2) - b * (1 / (2 * math.sqrt(b * x))) n_roots = 3 def newton_method(n_roots): roots = [] for n in range(1, n_roots + 1): x0 = ((2 * n - 1) * math.pi) / (2 * a) x1 = x0 - f(x0) / df(x0) while abs(x1 - x0) > eps: x0 = x1 x1 = x0 - f(x0) / df(x0) roots.append(x1) return roots def bisection_method(n_roots): roots = [] for n in range(1, n_roots + 1): a0 = ((2 * n - 1) * math.pi) / (2 * a) a1 = ((2 * n + 1) * math.pi) / (2 * a) x = (a0 + a1) / 2 while f(a0) * f(x) != 0: if f(a0) * f(x) < 0: a1 = x else: a0 = x x = (a0 + a1) / 2 if abs(f(x)) < eps: break roots.append(x) return roots def parabola_method(n_roots): roots = [] for n in range(1, n_roots + 1): a0 = ((2 * n - 1) * math.pi) / (2 * a) a1 = ((2 * n + 1) * math.pi) / (2 * a) x0 = a0 x1 = a1 x2 = (x0 + x1) / 2 while abs(x1 - x0) > eps: q1 = (f(x1) * f(x2) * (x0 - x1)) / ((f(x0) - f(x1)) * (f(x0) - f(x2))) q2 = (f(x0) * f(x2) * (x1 - x0)) / ((f(x1) - f(x0)) * (f(x1) - f(x2))) q3 = (f(x0) * f(x1) * (x2 - x0)) / ((f(x2) - f(x0)) * (f(x2) - f(x1))) x_new = x0 + q1 + q2 + q3 x0 = x1 x1 = x_new roots.append(x1) return roots newton_roots = newton_method(n_roots) bisection_roots = bisection_method(n_roots) parabola_roots = parabola_method(n_roots) print("Newton method roots: {}".format(newton_roots)) print("Bisection method roots: {}".format(bisection_roots)) print("Parabola method roots: {}".format(parabola_roots))