Example #1
0
from Polynomials import Polynomial
from Computation.RootFinding import bisection_method_convergents
from numpy import linspace
import matplotlib.pyplot as plt

fig = plt.figure()
fig.set_size_inches(10, 6)

P = Polynomial([-2,-1,0,1])
print(P)

x = linspace(0,2,30)
y = P.evaluate(x)[0]

def poly_eval(x):
    return P.evaluate(x)[0]

plt.plot(x,y)
plt.axhline(0)
con = bisection_method_convergents(0,2,poly_eval,10)
prev = 0
for ctr,pos in enumerate(con):
    plt.scatter(pos,poly_eval(pos),zorder=3,color='black')
    plt.plot([prev,pos],[4-ctr*.2,4-ctr*.2],color='black')
    print(pos)
    
    prev = pos
Example #2
0
from Polynomials import Polynomial

print("Number of Ways to Get a Sum with N Dice")

D1 = Polynomial([1] * 6)
D2 = D1**2
D3 = D1**3
D4 = D1**4

L = [D1**i for i in range(1, 5)]

for n, poly in enumerate(L, 1):
    for val, num in enumerate(poly, n):
        print(f"{val:<2} = {num}")
    print()
from Polynomials import Polynomial
from matplotlib import pyplot as plt

coef = [7, 2, 12, 9, 3, 31]
F = 101

P = Polynomial(coef, F)

x = [i for i in range(101)]
y = P.evaluate(x)

s = str(P)

title = r"${}$ {}".format(s[:-9], s[-9:])
plt.scatter(x, y)
plt.title(title)
Example #4
0
 def test_get_derivative_1(self):
     f = Polynomial('2x^3+3x+1')
     result = f.get_derivative()
     expected = '6x2+3'
     self.assertEqual(result, expected)
Example #5
0
from Polynomials import Polynomial, rational_roots
from random import randint

print("Examples of polynomials with rational roots.\n")

ctr = 0
while ctr < 3:
    co = [randint(-99, 99) for i in range(5)]

    #P = Polynomial([6,-7,0,1])
    P = Polynomial(co)
    R = rational_roots(P)

    if len(R) > 0:
        print(P)
        print(f"Roots: {R}")
        ctr += 1
        print()

print("Polynomials do not necessarily have any rational roots.")
Example #6
0
 def test_get_derivative_of_x_to_the_power_of_one(self):
     f = Polynomial('2x')
     result = f.get_derivative()
     expected = '2'
     self.assertEqual(result, expected)
Example #7
0
 def test_get_derivative_of_1_x(self):
     f = Polynomial('1x')
     result = f.get_derivative()
     expected = '1'
     self.assertEqual(result, expected)
Example #8
0
 def test_get_derivative_4(self):
     f = Polynomial('3x^2')
     result = f.get_derivative()
     expected = '6x'
     self.assertEqual(result, expected)
Example #9
0
 def test_get_derivative_of_a_constant(self):
     f = Polynomial('123')
     result = f.get_derivative()
     expected = '0'
     self.assertEqual(result, expected)
Example #10
0
from Rationals import bernoulli_number, Rational
from Polynomials import Polynomial
from Combinatorics import choose

for n in range(1, 9):
    P = Polynomial([0])
    for k in range(n + 1):
        b = bernoulli_number(n - k)
        c = choose(n, k)
        co = b * c
        P += Polynomial([0] * k + [co])

    print(P)
    print()
Example #11
0
 def test_get_derivative_2(self):
     f = Polynomial('x^4+10*x^3')
     result = f.get_derivative()
     expected = '4x3+30x2'
     self.assertEqual(result, expected)
from Polynomials import Polynomial
from Rationals import Rational

print(
    "Say we have a biased coin. It has P(Heads) = .6 and P(Tails) = .4 which we could represent as a Bernoulli distribution. However another option is to encode it as a polynomial generating function. That would be:"
)

Bern = Polynomial([.4, .6])
print(Bern)

print(
    "\nTHis is useful because the coefficients of polynomials distribute over each other when multiplying. That is exactly what happens when we try to calculate the probabilities associated with flipping the coin multiple times."
)

print("")

for i in range(2, 6):
    Bin = Bern**i
    print(round(Bin, 2))

print("""
Let's see why with two coin flips (removing decimals for ease of reading)
(6x + 4) * (6x + 4)
6x*6x + 6x*4 + 6x*4 + 4*4
36x^2 + 48x + 16
""")

print(
    "The probability of independent events both happening comes from multiplying together the probability of each. This is exactly what happens when we distribute the coefficients for polynomial multiplication, every pair gets multiplied together."
)
print(
Example #13
0
 def __init__(self, coef):
     assert len(coef) < 9
     self.poly = Polynomial(coef, modulus=2)
Example #14
0
from Polynomials import Polynomial

# The finite field GF(2^8) with 256 elements has various expressions

# The Rijndael polynomial
R = Polynomial([1, 1, 0, 1, 1, 0, 0, 0, 1], 2)


class Rijndael:
    def __init__(self, coef):
        assert len(coef) < 9
        self.poly = Polynomial(coef, modulus=2)

    def __add__(self, Q):
        assert type(self) == Rijndael
        assert type(Q) == Rijndael

        a = (self.poly + Q.poly) % R
        return Rijndael(a.coef)

    def __mul__(self, Q):
        assert type(self) == Rijndael
        assert type(Q) == Rijndael

        a = (self.poly * Q.poly) % R
        return Rijndael(a.coef)

    def __str__(self):
        c = [str(i) for i in reversed(self.poly.coef)]
        c = "".join(c)
        return f"{c:>8}"
Example #15
0
from Polynomials import Polynomial
from math import factorial, exp
import sys

try:
    x = float(sys.argv[1])
    m = [int(sys.argv[2])]
    for num in sys.argv[3:]:
        m.append(int(num))
except:
    print("x and (one or several) N (integers) must be provided")
    sys.exit(1)

n = sorted(m)  #sort degrees
#generate coefficients up to nmax
coeffs = [1 / factorial(k) for k in range(n[-1] + 1)]

poly = [None] * len(n)
for i in range(len(n)):
    poly[i] = Polynomial(coeffs[0:n[i] + 1])

print("Taylor approximation of n-th order:")
for i in range(len(n)):
    print("N=%g,   %g" % (n[i], poly[i](x)))
print("exact value e^x=%g" % exp(x))
from Polynomials import Polynomial

cA = [-14, 0, -12, 1]
cB = [5, -3, 1]
A = Polynomial(cA)
B = Polynomial(cB)

print(
    "For computation it is easiest to store polynomial is ascending order starting with the lowest coefficient. When writing them out is it traditional to do so starting with the highest coefficient."
)

print("\nBecause of this \npolynomial({}) = {}".format(cA, A))

print(
    "\n\nWe can do a lot of familiar arithmetic using polynomials. In the following examples\nA = ",
    A, "\nB = ", B)

print("\n")
print("A + B =", A + B)
print("A - B =", A - B)
print("A * B =", A * B)
print("A ^ 2 =", A**2)
print("A / B =", A / B)
print("A % B =", A % B)

C = A / B
D = A % B
if A == C * B + D:
    print("\nDivision works correctly")
else:
    print("\nSomething went wrong with division")