7

My code:

(* v1 = ripple minimum, v2 = ripple maximum *)
Clear[ripple, v1, v2, dc, rc, t0]; 
r = Solve[{v1 + (1 - v1) (1 - E^(-dc t0/rc)) == v2 && v2 E^(-(1 - dc) t0/rc) == v1 &&
       ripple == v2 - v1}, {v1, v2, ripple}]

which returns

enter image description here

Now I wanted to assign the expression for ripple to a function, and after a couple of failed attempts I came up with this:

ripple[t0_, rc_, dc_] := Evaluate[First[r][[3,2]]]

This works, but I don't know if this is good practice, and I don't want to get bad habits. So, what's the "right" way to do this?

stevenvh
  • 6,866
  • 5
  • 41
  • 64

1 Answers1

8

SetDelayed ( : = ) suppose to delay evaluation of the right hand side, but you enforce it anyway by Evaluate. So you are doing sorts of redundant things - see comment by @Mr.Wizard . To get a hang of the topic read tutorial Immediate and Delayed Definitions . In general I think it is more natural to base extraction of needed formula on the variable name rather than on indexes of solution list. It also improves code clarity:

ripple[t0_, rc_, dc_] = First[ripple /. r]

I hope your "shudder" of /. can be cured by Applying Transformation Rules ;-)

Dr. belisarius
  • 115,881
  • 13
  • 203
  • 453
Vitaliy Kaurov
  • 73,078
  • 9
  • 204
  • 355
  • Thanks. I guess I really should dive into that ReplaceAll... [shudders] – stevenvh Aug 12 '12 at 09:03
  • Any comments on my using SetDelayed instead of Set? (It looks like I can't use SetDelayed with the ReplaceAll) – stevenvh Aug 12 '12 at 09:21
  • @stevenvh The form: func[x_, y_] := Evaluate[ . . . ] serves no purpose. Symbols x and y are not localized with this form as Evaluate causes evaluation before that mechanism activates. Use = as shown. (ps what's wrong with /. ?) – Mr.Wizard Aug 12 '12 at 09:34
  • 1
    @Mr.Wizard - Oh, nothing wrong with it. On the contrary: when I look at some code it seems really powerful. I just can't get the hang of it completely yet. Sometimes a bit cryptic. I guess it will come "with time and sandwiches", as we say in Dutch :-) – stevenvh Aug 12 '12 at 09:42
  • @stevenvh I updated answer a bit – Vitaliy Kaurov Aug 12 '12 at 09:51