2
$\begingroup$

I have a function

y[r_] := D[otherfunction[r],t] +  D[r,t]; 

where $r$ can pick up a time dependence depending on the problem. When it does not I am having issues as it's returning 0[1] instead of 0. Is this because of the delayed := command? How to make it evaluate to zero when the time dependencies are lost?

Thanks

$\endgroup$
1
  • 1
    $\begingroup$ The whole setup is not really correct in terms of programming. You should never have function access anything that is not passed to it via its arguments. In your example, otherfunction and t are global. They should be instead be passed to the function via its arguments. So your function should have been y[r_,t_,f_] where f is the other function. This is the right way to do things. $\endgroup$
    – Nasser
    Commented Jul 17, 2023 at 20:51

2 Answers 2

3
$\begingroup$

You have always to write the arguments of a function, even if it is a dummy argument. With this you would write:

y[r_] := D[f[r[t]], t] + D[r[t], t];

Now, if r does not depend on t, like:

r[t_]= const;
y[r[t]]

0

And for t depended r;

r[t_] = const  t;
y[r[t]]

const + const Derivative[1][f][const t]

And for any argument without explicite t dependence:

y[r]

0
$\endgroup$
4
$\begingroup$

Let's shift our perspective to looking at a "time independent r" as "r[t] is constant for all t". This naturally extends to a time dependent case where "r[t] is not constant for all t". With this in mind, we can change r to r[t] and not lose any generality.

Then we can rewrite your expression as

y[r_] := D[otherfunction[r[t]], t] + D[r[t], t]

where r now needs to be given as a Function. For example

y[Function[{t}, t^2]]

2 t + 2 t otherfunction'[t^2]

There are also the "syntactic" reasons why your implementation isn't doing what you want it to (as in @Daniel Huber's excellent answer), but this is another way of thinking about "what the code means".

Alternatively, you can also use the total derivative Dt which has the documentation

All quantities not explicitly specified as constants are assumed to depend on the [arguments]

So for your example

Dt[otherfunction[r], t] + Dt[r, t]

Dt[r, t] + Dt[r, t] otherfunction'[r]

$\endgroup$
1
  • $\begingroup$ thank you for sharing your answer, if had more points would up vote you. $\endgroup$
    – ninPHX
    Commented Jul 17, 2023 at 18:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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