Polynomials in sagemath

Some useful global variables:

Natural Numbers (semiring)NN
Integer RingZZ
Rational FieldQQ
Real FieldRR
Complex FieldCC

At first we create a polynomial ring over a field/ring

In [1]:
R.<x> = PolynomialRing(QQ)
R.<x> = QQ[]

Also a multivariate polynomial ring is possible

In [2]:
R.<x,y> = PolynomialRing(QQ)

Another useful way to get x

In [3]:
x = PolynomialRing(QQ, 'x').gen()

Now we can declare some polynomial:

In [4]:
p = x^3 + 0.3*x^2 - x - 0.3
p
Out[4]:
x^3 + 0.300000000000000*x^2 - x - 0.300000000000000

How to evaluate the value at some given point a?

In [5]:
p(-0.1)
Out[5]:
-0.198000000000000

We can also factor p

In [6]:
p.factor()
Out[6]:
(x - 1.00000000000000) * (x + 0.300000000000000) * (x + 1.00000000000000)

At next we calculate the roots

In [7]:
p.roots()
Out[7]:
[(-1.00000000000000, 1), (-0.300000000000000, 1), (1.00000000000000, 1)]

A short introduction into plotting polynomials

In [8]:
plot(p)
Out[8]:

In this example, the domain is chosen by sagemath. In the following, we supply minimum and maximum x-value explicitly:

In [9]:
var('s')
plot(p(s), (s, -5, 5))
Out[9]:

Calculate the derivative

In [10]:
p_diff = p.diff()
p_diff
Out[10]:
3.00000000000000*x^2 + 0.600000000000000*x - 1.00000000000000

Combine plots and zoom in

In [11]:
plot(p(s), (s, -10, 10)) + plot(p_diff(s), (s, -10, 10), color='red')
Out[11]:

Calculate the integral

In [12]:
p_int = p.integral()
p_int
Out[12]:
0.250000000000000*x^4 + 0.100000000000000*x^3 - 0.500000000000000*x^2 - 0.300000000000000*x

Plot the integral and the polynomial

In [13]:
plot(p(s), (s, -10, 10)) + plot(p_int(s), (s, -10, 10), color='green')
Out[13]:

One particular case of a polynomial is a power series. Sine is a trigonometric function defined as a power series:

In [14]:
x = var('x')
f = sin(x)
s = f.series(x, 5)
show(s)
show(s(x=5))

Now we can draw the sine and the polynomial to see the differences

In [15]:
plot(s.truncate(), xmin=-pi, xmax=pi) + plot(f, color='green', xmin=-pi, xmax=pi)
Out[15]: