Re: Piecewise function generator
- To: mathgroup at christensen.cybernetics.net
- Subject: [mg1189] Re: Piecewise function generator
- From: Count Dracula <lk3a at kelvin.seas.virginia.edu>
- Date: Mon, 22 May 1995 01:52:46 -0400
- Organization: University of Virginia
In Message-ID: <3p8shv$6b8 at news0.cybernetics.net> Daryl Reece writes: > I want to generate a piecewise continuous linear function by giving a > function, call it F, a list of {x,y} values defining the corners of the > function, e.g., pts={{20,0.08},{50,0.8},{250,0.8},{5000,0.004}} If no symbolic expression for the function is needed Interpolation[pts, InterpolationOrder -> 1] is the briefest way. If symbolic expressions are needed, Roman Maeder's program MakeFunctions.m in the Packages directory shows a way to generate the rules needed. For instance, the program below can be used. __________________________________________________________________________________ LinearFunction::usage = "LinearFunction[f, {{x0, a}, {x1, b}}] defines rules for f such that f[x] = a for x = x0, f[x] = b for x = x1 and f is linear between x0 and x1. LinearFunction[f, pointslist] defines rules for a piecewise linear function passing through the (x, y) coordinates in the list pointslist." MakeRuleConditional::usage = "MakeRuleConditional[f, x, rhs, cond] globally defines the rule f[x_] := rhs /; cond." Off[ RuleDelayed::rhs ] SetAttributes[MakeRuleConditional, HoldAll] MakeRuleConditional[f_Symbol, var_Symbol, rhs_, condition_] := (f[var_] := rhs /; condition) LinearFunction[f_Symbol, {{x0_, a_}, {x1_, b_}}] := With[{slope = (b-a)/(x1-x0)}, MakeRuleConditional[f, x, a + (x-x0) slope, x0 <= x <= x1]; ] LinearFunction[f_Symbol, pointslist_List] := (Map[ LinearFunction[f, #1] &, Partition[ Union[pointslist], 2, 1]]; Null) __________________________________________________________________________________ Example: In[2]:= pts = {{20,0.08},{50,0.8},{250,0.8},{5000,0.004}}; In[3]:= LinearFunction[f, pts] In[4]:= ?f Global`f f[x_] := 0.08 + (x - 20)*0.024 /; 20 <= x <= 50 f[x_] := 0.8 + (x - 50)*0. /; 50 <= x <= 250 f[x_] := 0.8 + (x - 250)*-0.0001675789473684211 /; 250 <= x <= 5000 In[4]:= pts2 = { {2,0.08}, {5,0.8}, {2.5,0.75}, {4,4}, {3, 9} }; In[5]:= LinearFunction[g, pts2] In[6]:= ?g Global`g g[x_] := 0.08 + (x - 2)*1.34 /; 2 <= x <= 2.5 g[x_] := 0.75 + (x - 2.5)*16.5 /; 2.5 <= x <= 3 g[x_] := 9 + (x - 3)*-5 /; 3 <= x <= 4 g[x_] := 4 + (x - 4)*-3.2 /; 4 <= x <= 5 -- ___________________________________________________________________________________ Levent Kitis lk3a at cars.mech.virginia.edu lk3a at kelvin.seas.virginia.edu University of Virginia Department of Mechanical, Aerospace, and Nuclear Engineering ___________________________________________________________________________________