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

Thread[Round[#],array]

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.

Awesome! How does it work…?

– quantum_loser

May 3 at 12:42

@quantum_loser Added to answer

– happy fish

May 3 at 12:44

1

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.

– JasonB

May 3 at 12:51

@JasonB you are right, I didn’t think much, only made it work with the example

– happy fish

May 3 at 12:53

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

ClearAll[f]

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

f[2, 3]

30.6306

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

f[2, 3]

30.5