polynomial and piecewise defined functions
In [1]:
from Goulib.notebook import *
from Goulib.polynomial import *
from Goulib import itertools2, plot
In [2]:
p1=Polynomial([-1,1,3]) # inited from coefficients in ascending power order
p1 # Latex output by default
Out[2]:
In [3]:
p2=Polynomial('- 5x^3 +3*x') # inited from string, in any power order, with optional spaces and *
p2.plot()
Out[3]:
In [4]:
[(x,p1(x)) for x in itertools2.linspace(-1,1,11)] #evaluation
Out[4]:
In [5]:
p1-p2+2 # addition and subtraction of polynomials and scalars
Out[5]:
In [6]:
-3*p1*p2**2 # polynomial (and scalar) multiplication and scalar power
Out[6]:
In [7]:
p1.derivative()+p2.integral() #integral and derivative
Out[7]:
In [8]:
from Goulib.motion import *
Polynomials are very handy to define Segments as coefficients can easily be determined from start/end conditions. Also, polynomials can easily be integrated or derivated in order to obtain position, velocity, or acceleration laws from each other.
Motion defines several handy functions that return SegmentPoly matching common situations
In [9]:
seg=Segment2ndDegree(0,1,(-1,1,2)) # time interval and initial position,velocity and constant acceleration
seg.plot()
Out[9]:
In [10]:
seg=Segment4thDegree(0,0,(-2,1),(2,3)) #start time and initial and final (position,velocity)
seg.plot()
Out[10]:
In [11]:
seg=Segment4thDegree(0,2,(-2,1),(None,3)) # start and final time, initial (pos,vel) and final vel
seg.plot()
Out[11]:
In [12]:
from Goulib.interval import *
Interval(5,6)+Interval(2,3)+Interval(3,4)
Out[12]:
In [13]:
from Goulib.piecewise import *
The simplest are piecewise continuous functions. They are defined by $(x_i,y_i)$ tuples given in any order.
$f(x) = \begin{cases}y_0 & x < x_1 \\ y_i & x_i \le x < x_{i+1} \\ y_n & x > x_n \end{cases}$
In [14]:
p1=Piecewise([(4,4),(3,3),(1,1),(5,0)])
p1 # default rendering is LaTeX
Out[14]:
In [15]:
p1.plot() #pity that matplotlib doesn't accept large LaTeX as title...
Out[15]:
By default y0=0 , but it can be specified at construction.
Piecewise functions can also be defined by adding (x0,y,x1) segments
In [16]:
p2=Piecewise(default=1)
p2+=(2.5,1,6.5)
p2+=(1.5,1,3.5)
p2.plot(xmax=7,ylim=(-1,5))
Out[16]:
In [17]:
plot.plot([p1,p2,p1+p2,p1-p2,p1*p2,p1/p2],
labels=['p1','p2','p1+p2','p1-p2','p1*p2','p1/p2'],
xmax=7, ylim=(-2,10), offset=0.02)
Out[17]:
In [18]:
p1=Piecewise([(2,True)],False)
p2=Piecewise([(1,True),(2,False),(3,True)],False)
plot.plot([p1,p2,p1|p2,p1&p2,p1^p2,p1>>3],
labels=['p1','p2','p1 or p2','p1 and p2','p1 xor p2','p1>>3'],
xmax=7,ylim=(-.5,1.5), offset=0.02)
Out[18]:
In [21]:
from math import cos
f=Piecewise().append(0,cos).append(1,lambda x:x**x)
f
Out[21]:
In [23]:
f.plot()
Out[23]: