I have a system of equations in which variables are indexed as:

8 x[1] + 2 y[1] == 2;
3 x[1] - 5 y[1] == 7;

The solution obtained from my model is of the form:

sol = {{x[1.] -> 12/23, y[1.] -> -(25/23)}};

As seen, the variable index looks like a Machine Number (x[1.] and y[1.]). Therefore, I cannot map the sol onto the equations to check if they are satisfied.

I simply want the sol to be:

{{x[1] -> 12/23, y[1] -> -(25/23)}};

How can I get rid of the Machine Numbers to be the variable index?

  • 1
    $\begingroup$ How are you solving the equations? If I simply write Solve[{8 x[1] + 2 y[1] == 2, 3 x[1] - 5 y[1] == 7}] I get {{x[1] -> 12/23, y[1] -> -25/23}} with no machine-precision numbers involved. $\endgroup$
    – eyorble
    May 6 '20 at 16:48
  • $\begingroup$ @eyorble: You are right. I also get the same thing as you. But in my model (bold text in my message) the solution is produced by using x[1.], y[1.] etc. That is why I indicated that this solution is specific to my model. I solve the model by FindRoot[CGEmodel /. Flatten[{greekParamAssign, smallParamAssign}], initialValues, AccuracyGoal -> 3, PrecisionGoal -> 30] // N; $\endgroup$ May 6 '20 at 16:52
  • 1
    $\begingroup$ You can do sol /. {x[n_] :> x[Rationalize[n]], y[n_] :> y[Rationalize[n]]}. $\endgroup$ May 6 '20 at 17:01
  • 1
    $\begingroup$ Ok, assuming no other head-argument combinations appear that should not be tampered with, try sol /. head_[n_] :> head[Rationalize[n]]. $\endgroup$ May 6 '20 at 17:26
  • 2
    $\begingroup$ Please show some effort on your own here, the matter is just to deal with a Sequence of arguments (n__) instead of a single one. You have not mentioned any of these details in your question about 1000 variables and several indices. $\endgroup$ May 6 '20 at 17:53

For one or more indices on different variable names, the following should work:

sol /. x_[n__?NumericQ] ->  :> x @@ Rationalize[{n}]

Of course, one can just Rationalize the whole thing, but that changes stuff on the RHS too, not only the indices.

A way of avoiding this problem all together is to not apply N to a whole expression containing variables indexed by numbers in the first place, but instead apply N only to the numerical stuff.

  • 1
    $\begingroup$ First, I like to thank you for your code, which works as expected. Also, I will be careful about the use of N. My problem is solved... $\endgroup$ May 6 '20 at 20:05
  • 2
    $\begingroup$ Another trick you can use is SetAttributes[x, NHoldAll]. This will prevent N from affecting arguments of x. So for example, N[x[1]] will just return x[1]. $\endgroup$ May 7 '20 at 14:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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