Warning
This page is located in archive. Go to the latest version of this course pages. Go the latest version of this page.

6. Seznamy / pole

Polynomy

from math import pow
import matplotlib.pyplot as plt
 
def nacti_data(filename):
    'funkce pro nacteni rady celych cisel ze souboru'
    f = open(filename, 'r')
    a = f.readline()
    f.close()   # uzavreni souboru
    return list(map(int, a.split()))
 
def printPoly(seznam):
    'tisk polynomu ve tvaru 1 + x - 2x^3'
    first = True
    sign = ""
    for i in range(len(seznam)):
        # nevypisujeme nulove koeficienty
        if seznam[i] == 0: continue
        if i == 0:
            print(seznam[i], end=" ")
            first = False
        else:
            sign = ""
            if seznam[i] > 0:
                if first == False:
                    sign = "+"
            first = False
            # automaticke vynuceni znamenka u kladneho cisla (vzdy)
            # print("{0:+}x^{1}".format(seznam[i], i), end=" ")
            # kladne znamenko se nevypisuje u prvniho kladneho clenu
            print("{}{}x^{}".format(sign, seznam[i], i), end=" ")
    print("")
 
# na disku mam soubor poly.txt
# 0 -2 3 -2
 
def valuePoly(p, v):
    'vypocet hodnoty polynomu p v bode v'
    s = 0
    for i in range(len(p)):
        s += p[i]*pow(v, i)
    return s
 
a = nacti_data("poly.txt")
printPoly(a)
s = valuePoly(a, 10)
print(s)
 
# pip3 install matplotlib --user
# import matplotlib.pyplot as plt
y = []
x = []
s = -5
for i in range(100):
     s += 0.1
     x.append(s)
     y.append(valuePoly(a, s))
plt.figure(1)
plt.plot(x,y)
plt.show()

courses/bab37zpr/solutions/lab06.txt · Last modified: 2019/11/11 14:27 by viteks