-
Notifications
You must be signed in to change notification settings - Fork 0
/
false_position.py
63 lines (52 loc) · 1.89 KB
/
false_position.py
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
# -*- coding: utf-8 -*-
"""false_position.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1v-3ibHQTF_oadzBLf0hdRyO44ulT6ucL
"""
import random
def evaluate_polynomial(coefficients, x):
result = 0
power = len(coefficients) - 1
for coeff in coefficients:
result += coeff * (x ** power)
power -= 1
return result
def false_position(array,x,y,epsilon=1e-6, max_iterations=100):
if evaluate_polynomial(array, x) * evaluate_polynomial(array, y) >= 0 or x >= y:
while evaluate_polynomial(array, x) * evaluate_polynomial(array, y) >= 0 or x >= y:
x = random.randint(-9, 9)
y = random.randint(-9, 9)
f_x = evaluate_polynomial(array, x)
f_y = evaluate_polynomial(array, y)
iterations = 0
while abs(f_y - f_x) >= epsilon and iterations < max_iterations:
x_new = (x * f_y - y * f_x) / (f_y - f_x)
f_new = evaluate_polynomial(array, x_new)
if f_new == 0:
break
if f_new * f_x < 0:
y = x_new
f_y = f_new
else:
x = x_new
f_x = f_new
iterations += 1
if iterations == max_iterations:
print("Maximum iterations reached. The method may not have converged.")
return x_new
print("\tFalse position method\t")
d = int(input("Enter the highest degree of the polynomial: "))
array = []
for i in range(d + 1):
f = d - i
c = int(input("Enter the coefficient of x ^"+str(f)+" : "))
array.append(int(c))
a = int(input("Enter a value for a: "))
b = int(input("Enter a value for b: "))
result = evaluate_polynomial(array, a)
res = evaluate_polynomial(array, b)
print(f"The result of the polynomial with x = {a} is {result}")
print(f"The result of the polynomial with x = {b} is {res}")
root = false_position(array, a, b)
print(f"The root of the polynomial is {root}")