Menu

[r3211]: / trunk / py4science / examples / polyroots1d.py  Maximize  Restore  History

Download this file

52 lines (42 with data), 1.1 kB

 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
#!/usr/bin/env python
"""Simple demonstration of polynomials and root finding."""
import numpy as N
import scipy as S
import pylab as P
def plot_poly(x,y,roots):
"""Simple utility to make a charting screen with x/y axes"""
P.figure()
P.axhline(0,color='g')
P.axvline(0,color='g')
P.grid()
P.plot(x,y,'b-')
P.scatter(roots.real,roots.imag,s=80,c='r')
P.xlabel('Re')
P.ylabel('Im')
# Create the coefficients for a polynomial with nroots_minus1 at x=-1, one
# root at -2 and one root at 1:
nroots_minus1 = 10
coefs = reduce(N.convolve,[[1,1]]*nroots_minus1+[[1,2],[1,-1]])
# Construct the polynomial and get its roots
pol = S.poly1d(coefs)
roots = pol.r
print 'Polynomial p(x):\n',pol,'\n'
print 'p(x) built with coefs:',coefs
print 'Roots of p(x):',roots
# Plot p(x)
x = N.linspace(-4,4,400)
y = pol(x)
# Show roots
plot_poly(x,y,roots)
P.xlim(-3,2)
P.ylim(-250,100)
P.title('All roots')
# Set limits and grid to make the plot clear
#P.ylim(-40,40)
plot_poly(x,y,roots)
eps = 0.05
P.xlim(-1-eps,-1+eps)
P.ylim(-eps,eps)
P.title('Root cluster around $x=-1$')
# Display on screen
P.show()
Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.