119
140
3 Functionsandbranching
a) Make twoPythonimplementationsof suchanindicator function,
onewithadirecttestifx∈[L,R]andonethatexpressestheindicator
functionintermsofHeavisidefunctions(3.24):
I(x;L,R)=H(x−L)H(R−x).
(3.27)
b)Makeatestfunctionforverifyingtheimplementationofthefunctions
ina).Checkthatcorrectvaluesarereturnedforsomex<L,x=L,
x=(L+R)/2,x=R,andsomex>R.
Filename:indicator_func.py.
Exercise3.26:Implementapiecewiseconstantfunction
Piecewiseconstantfunctionshavealotofimportantapplicationswhen
modelingphysicalphenomenabymathematics.Apiecewise constant
functioncanbedefinedas
f(x)=
v
0
,x∈[x
0
,x
1
),
v
1
,x∈[x
1
,x
2
),
.
.
.
v
i
x∈[x
i
,x
i+1
),
.
.
.
v
n
x∈[x
n
,x
n+1
]
(3.28)
Thatis,wehaveaunionofnon-overlappingintervalscoveringthedomain
[x
0
,x
n+1
],andf(x) isconstant ineachinterval.One example isthe
functionthatis-1on[0,1],0 on[1,1.5],and4on[1.5,2],where we
withthenotationin(3.28)havex
0
=0,x
1
=1,x
2
=1.5,x
3
=2and
v
0
=−1,v
1
=0,v
3
=4.
a) MakeaPythonfunctionpiecewise(x, , data)forevaluatingapiece-
wiseconstantmathematicalfunctionasin(3.28)atthepointx.The
dataobjectisalistofpairs(v
i
,x
i
)fori=0,...,n.Forexample,datais
[(0, -1), , (1, , 0), (1.5, 4)]intheexamplelistedabove.Sincex
n+1
isnotapartofthedataobject,wehavenomeansfordetectingwhether
xistotherightofthelastinterval[x
n
,x
n+1
],i.e.,wemustassumethat
theuserofthepiecewisefunctionsendsinanx≤x
n+1
.
b) Designsuitabletestcasesforthefunctionpiecewiseandimplement
theminatestfunctiontest_piecewise().
Filename:piecewise_constant1.py.
Exercise3.27:Applyindicatorfunctions
Implementpiecewiseconstantfunctions,asdefinedinExercise3.26,by
observingthat