1
$\begingroup$

Say I have two replacement rules in terms of interpolating functions.

Rule1 = {z -> Interpolation[Table[{i, i^2 + i}, {i, 0, 2, 0.1}]]};

Rule2 = {x -> Interpolation[Table[{i, Sin[i] + i}, {i, 0, 2, 0.1}]]};

Now consider I have a function which I cannot evaluate by any other means except only by replacing the above rules.

func = Sin[x z]/(x + z)^2 /. Flatten[{Rule1, Rule2}]

What is the way to get the function value at any i?

Note: Actually, in a multibody dynamics code I have obtained 6 variables as replacement rules of interpolating functions. Now I need to compute another quantity which is a very large function of these variables.

$\endgroup$

2 Answers 2

2
$\begingroup$

Not using replacement rules (yet), let's see a model of what will work:

Rule1z = Interpolation[Table[{i, i^2 + i}, {i, 0, 2, 0.1}]];
Rule2x = Interpolation[Table[{i, Sin[i] + i}, {i, 0, 2, 0.1}]];
fun[i_] = Sin[Rule2x[i] Rule1z[i]]/(Rule2x[i] + Rule1z[i])^2;
fun[1.2]

(* -0.0267361 *)

Following that model, we can use the replacement rules this way:

Rule1 = {z -> Interpolation[Table[{i, i^2 + i}, {i, 0, 2, 0.1}]]};
Rule2 = {x -> Interpolation[Table[{i, Sin[i] + i}, {i, 0, 2, 0.1}]]};
RuleAz = z /. Rule1;
RuleBx = x /. Rule2;
fun2[i_] = Sin[RuleBx[i] RuleAz[i]]/(RuleBx[i] + RuleAz[i])^2;
fun2[1.2]

(* -0.0267361 *)

This suggests a more compact version that also works.

fun3[i_] = Sin[x[i] z[i]]/(x[i] + z[i])^2 /. Flatten[{Rule1, Rule2}];
fun3[1.2]

(* -0.0267361 *)
$\endgroup$
1
$\begingroup$

One alternative is to supply an argument to the InterpolatingFunction in each rule. This way the replacement replaces a variable representing a number with an expression representing the value of an InterpolatingFunction. It replace something with a thing of the same kind (a number).

Rule1[k_] = {z -> Interpolation[Table[{i, i^2 + i}, {i, 0, 2, 0.1}]][k]};
Rule2[k_] = {x -> Interpolation[Table[{i, Sin[i] + i}, {i, 0, 2, 0.1}]][k]};

Using func as an expression depending on i, with two evaluation options:

func = Sin[x z]/(x + z)^2 /. Flatten[{Rule1[i], Rule2[i]}];

func /. i -> 1
(*  -0.0349188  *)

Block[{i = 1}, func]
(*  -0.0349188  *)

Defining func as a function:

ClearAll[func];
func[i_] = Sin[x z]/(x + z)^2 /. Flatten[{Rule1[i], Rule2[i]}];

func[1]
func[1.2]
(*  -0.0349188  *)
(*  -0.0267361  *)
$\endgroup$

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.