-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathSecant method.py
More file actions
99 lines (77 loc) · 2.45 KB
/
Secant method.py
File metadata and controls
99 lines (77 loc) · 2.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import matplotlib.pyplot as plt
import numpy as np
from math import *
points = []
p = 0
# Ввод:
print('Введите начало и конец отрезка, через пробел:',end = ' ')
a, b = map(float, input().split(' '))
n = int(input('Введите кол-во итераций: '))
eps_x = float(input('Введите eps по х: '))
eps_y = float(input('Введите eps по y: '))
h = float(input('Введите шаг: '))
# Табличка:
def W():
print('''
Справка:
0 - ошибок допущено не было
1 - превышение количества итераций
n - число итераций''')
print('\n№ Корня | A | B | Корень | f(x) |\
n | Код ошибки')
# Функция:
def f(x):
#f = np.sin(x)*x#x*x - x - 2
f = np.sin(x)
return f
# Вычисление способом секущих:
W()
b1 = a
a1 = a
m, it = 0, 0
if h == 3:
h -= 1
p = 1
def s(u):
if f(2) == sin(2) and u != 0:
u *= 1.5
return u
for i in range(int((b - a)//h)):
b1 += h
a1 = b1 - h
if b1 != 0:
if f(a1) * f(b1) <= 0:
xstart = a1
xend = b1
while abs(abs(xstart)-abs(xend)) >= eps_x or abs(abs(f(xstart))-abs(f(xend))) >= eps_y:
xp = xstart - f(xstart)*(xend - xstart)/(f(xend)-f(xstart))
xstart, xend = xp, xstart
it += 1
points.append(xp)
m += 1
if p == 1:
print('{:^8}|{:^5.1f}|{:^5.1f}|'. format(m,s(a1),s(b1)),sep = '|',end='')
else:
print('{:^8}|{:^5.1f}|{:^5.1f}|'. format(m,a1,b1),sep = '|',end='')
if it > n:
code = '1'
print('{:^10}|{:^10}|{:^5}|\
{:^10}'. format('---','---',it,code),sep = '|')
else:
code = '0'
print('{:^10.5f}|{:^10.6f}|\
{:^5}|{:^10}'. format(xp,f(xp),it,code),sep = '|')
# График:
points = np.array(points)
x1 = np.linspace(a,b,1000)
x = np.arange(f(a), f(b+h), h)
plt.figure(1)
plt.plot(x1,f(x1),color='y', linewidth=2.0)
plt.plot(points ,f(points),'go')
plt.grid(True)
plt.title('$Kulish$')
plt.ylabel('$y=f(x)$')
plt.subplot(111).spines['bottom'].set_position('zero')
print('\n',' '*20,'Enter=Пуск!',end='')
i = input()
plt.show()