Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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?

share|improve this question
    
Related: stackoverflow.com/q/5319771/618728 –  Mr.Wizard Aug 12 '12 at 9:41
    
@Mr.Wizard - Thanks for the link. Admittedly, a rival site :-), but they seem friendly enough :-) –  stevenvh Aug 12 '12 at 10:11
add comment

1 Answer 1

up vote 8 down vote accepted

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 ;-)

share|improve this answer
    
Thanks. I guess I really should dive into that ReplaceAll... [shudders] –  stevenvh Aug 12 '12 at 9: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 9: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 9: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 9:42
    
@stevenvh I updated answer a bit –  Vitaliy Kaurov Aug 12 '12 at 9:51
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.