Hong-Phuc Bui
10 days ago fd66402c90a63cf8ce455c3614b9160884f74c61
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
#from turtle import Turtle
import turtle
 
class Polynomial:
    def __init__(self, *argv: float):
        if len(argv) < 1:
            raise ValueError("A Polynomial has at least one coefficient.")
        if argv[-1] == 0:
            raise ValueError("The coefficient at the highest degree must not be zero.")
        self.__coefficients = tuple(argv)
        self.__order = len(argv)
 
    def  evaluate(self, x: float) -> tuple[float, list[float]]:
        p = self.__coefficients[-1]
        c = [p]
        for ak in self.__coefficients[-2::-1]:
            p = ak + (p * x)
            c.insert(0, p)
        return c[0], c[1:]
 
    def order(self):
        return self.__order
 
    def __add__(self, other: "Polynomial") -> "Polynomial":
        if not isinstance(other, Polynomial):
            raise ValueError("Operator + is only applicable for Polynomial.")
        coefficients = []
        if self.__order > other.__order:
            low_order = other.__order
            heigh_order = self.__order
            higher_coefficients = self.__coefficients
        else:
            low_order = self.__order
            heigh_order = other.__order
            higher_coefficients = other.__coefficients
 
        for i in range(0, low_order):
            coefficients.append(self.__coefficients[i] + other.__coefficients[i])
        for j in range(i+1, heigh_order):
            coefficients.append(higher_coefficients[j])
        return Polynomial(*coefficients)
 
    def __getitem__(self, key):
        return self.__coefficients[key]
 
 
    def __repr__(self) -> str:
        coe = []
        for c in self.__coefficients:
            coe.append(f'{c}')
        return ' '.join(coe)
 
def plot_polynomial(t:turtle.Turtle, p:Polynomial, width=500, height=500):
    x_value = []
    y_value = []
    n = 9
    delta = 2 * width / (n-1)
    x0 = -width
    for i in range(0, n):
        y0 = p.evaluate(x0)[0]
        x_value.append(x0)
        y_value.append(y0)
        print(x0, y0)
        x0 = x0 + delta
    y_min = min(y_value)
    y_max = max(y_value)
    m = height - (2*height)/(y_max - y_min) * y_max
    w = lambda y : 2*height/(y_max - y_min) * y + m
    for i in range(0, n):
        x = x_value[i]
        y = y_value[i]
        y = w(y)
        print(x,y)
        t.goto(x,y)
    pass