1
$\begingroup$

I am trying to define a function with a lot of input variables, and some of the inputs are used to define other input variables. If I define them outside of the function and then pass them in I don't get an issue, but if I do the following then I get an issue

SolveSEIRs[n_: 500,
L_: RandomReal[{3.9,5.9}],
Cinc_: RandomReal[{Max[L,4.8],6.8}],
etc...

The error message that I am getting states...

"RandomReal: The endpoints specified by {Max[4.8,L],6.8} for the endpoints
of the uniform distribution range are not real-valued"

I have tried to look online for solutions to this problem, but I feel as though this might be a slightly specific issue, or that I am unable to describe it effectively due to being new to Mathematica.

Any help is appreciated.

$\endgroup$

1 Answer 1

1
$\begingroup$

You can do this with polymorphic definitions:

SolveSEIRs[] := SolveSEIRs[500];
SolveSEIRs[n_] := SolveSEIRs[n, RandomReal[{3.9, 5.9}]];
SolveSEIRs[n_, L_] := SolveSEIRs[n, L, RandomReal[{Max[L, 4.8], 6.8}]];
SolveSEIRs[n_, L_, Cinc_] := WhateverHappensHere[n, L, Cinc];

COMMENT

This might be too tangential, but my general advice is to avoid the default argument value syntax altogether. It can make for complications both in understanding your functions and also in how the evaluator actually interprets those defaults. Polymorphic definitions (as I showed) and using options are both preferable, in my estimation.

$\endgroup$
3
  • $\begingroup$ Thank you for your answer - so does this mean that for 13 input variables I would need to define 14 of these functions? Also, this situation occurs three times again where I am using an input variable in a RandomReal function to define another input variable, does that affect how I would use this method to create my function? $\endgroup$ Commented Oct 12, 2022 at 17:26
  • $\begingroup$ not necessarily. It depends on the details and the semantics of your arguments. $\endgroup$
    – lericr
    Commented Oct 12, 2022 at 17:27
  • $\begingroup$ This seems to me to be very strange design. I can't provide feedback without knowing your context, but just specifying the default value to be random is itself kind of weird. On top of that, creating these dependencies between arguments is just fraught. My gut tells me there's a better way of going about this altogether. $\endgroup$
    – lericr
    Commented Oct 12, 2022 at 17:30

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.