I have a complicated function that is a combination of floating-point numbers and variables. I want all the numbers rounded off, but I have no clue how to do this. For example I would want

f[x_,y_]:=3.23425124`x^2 + 5.8978587`y

To become

f[x_,y_]:=3.2x^2 + 5.9y

If it were an array I could have something like


But with a function what to do is not clear.


2 Answers 2

3.23425124` x^2 + 5.8978587` y /. Times[a_, b_] :> Times[Round[a, 0.1], b]
(*3.2 x^2 + 5.9 y*)

coefficient * variable is of Times[coefficient, variable] in full form, therefore you can use this pattern to match and round only the coefficient.

  • $\begingroup$ Awesome! How does it work...? $\endgroup$ May 3, 2016 at 12:42
  • $\begingroup$ @quantum_loser Added to answer $\endgroup$
    – vapor
    May 3, 2016 at 12:44
  • 1
    $\begingroup$ It would be more versatile to do /. a_?NumberQ :> Round[a, .1] as the replacement rule, then it would catch numbers in the denominators and not just simple products. $\endgroup$
    – Jason B.
    May 3, 2016 at 12:51
  • $\begingroup$ @JasonB you are right, I didn't think much, only made it work with the example $\endgroup$
    – vapor
    May 3, 2016 at 12:53

It's unclear what exactly is an input but here's my interpretation:

f[x_, y_] := 3.23425124` x^2 + 5.8978587` y;

f[2, 3]
DownValues[f] = DownValues[f] /. n_?NumericQ :> RuleCondition@Round[n, 0.1];

f[2, 3]

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.