Skip to content

Instantly share code, notes, and snippets.

@wthoutanymmries
Created May 5, 2021 21:21
Show Gist options
  • Select an option

  • Save wthoutanymmries/0b9906e60b68c644f3fe75b2ce384f18 to your computer and use it in GitHub Desktop.

Select an option

Save wthoutanymmries/0b9906e60b68c644f3fe75b2ce384f18 to your computer and use it in GitHub Desktop.
import numpy as np
# (x-4)^3(x-16)(x-21)
p = np.poly1d([1, -49, 828, -5872, 18496, -21504])
print(p)
# roots = np.array([4] * 2019 + [16, 21], dtype=object)
# p = np.poly1d(roots, True)
bounds = [1, 2021]
crit_points = [
x for x in p.deriv().r if x.imag == 0 and bounds[0] < x.real < bounds[1]
]
print(f'Границы: {bounds}')
print()
y = [p(point) for point in crit_points]
index_of_min = y.index(min(y))
print('min:')
print(f' x: {crit_points[index_of_min]} y: {y[index_of_min]}')
index_of_max = y.index(max(y))
print('min:')
print(f' x: {crit_points[index_of_max]} y: {y[index_of_max]}')
# (x-4)^3(x-16)(x-21)
poly = [
[4, 3],
[16, 1],
[21, 1]
]
epsilon = 0.001
less_epsilon = 0.00001
def evaluate_poly(poly, x):
result = 1
for root in poly:
result = result * (x - root[0]) ** root[1]
return result
def dichotomy_min(a, b, epsilon, poly):
while b - a > 0.001:
p = (b + a) / 2 - 0.00001
q = (b + a) / 2 + 0.00001
if evaluate_poly(poly, p) < evaluate_poly(poly, q):
b = q
else:
a = p
return (b + a) / 2
def dichotomy_max(a, b, epsilon, poly):
while b - a > 0.001:
p = (b + a) / 2 - 0.00001
q = (b + a) / 2 + 0.00001
if evaluate_poly(poly, p) > evaluate_poly(poly, q):
b = q
else:
a = p
return (b + a) / 2
x = []
for i in range(len(poly) - 1):
x.append(
dichotomy_min(poly[i][0], poly[i + 1][0], less_epsilon, poly)
)
y = [evaluate_poly(poly, _) for _ in x]
index_of_min = y.index(min(y))
print('min:')
print(f' x: {x[index_of_min]} y: {y[index_of_min]}')
x = []
for i in range(len(poly) - 1):
x.append(
dichotomy_max(poly[i][0], poly[i + 1][0], less_epsilon, poly)
)
y = [evaluate_poly(poly, _) for _ in x]
index_of_max = y.index(max(y))
print('max:')
print(f' x: {x[index_of_max]} y: {y[index_of_max]}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment