2
$\begingroup$

does Mathematica have built in functionality to round the coefficients of a polynomial to a certain accuracy. Say, we do

Print[0.2134320980x^2+0.0023432x]

Can we wrap a function around the expression in the print so that the output is

0.213x^2+0.002x

I tried NumberForm but this rounds messes with the exponent. Thank you!

$\endgroup$
4
  • $\begingroup$ If exponents are integers then you can use quick approach: 0.2134320980 x^2 + 0.0023432 x /. r_Real :> Round[r, .001] $\endgroup$
    – Kuba
    Jun 14, 2014 at 20:16
  • $\begingroup$ works pretty well. can it be also done that it adds zeros if the original number was too short? $\endgroup$ Jun 14, 2014 at 20:22
  • $\begingroup$ @kuba - yours answer would also round the exponents, which works in this case, but not for multi-digit exponents. The question was: "Round only coefficients". $\endgroup$
    – eldo
    Jun 14, 2014 at 20:48
  • $\begingroup$ @ kuba - OK, I have to improve my reading, sorry for that :) $\endgroup$
    – eldo
    Jun 14, 2014 at 20:50

2 Answers 2

3
$\begingroup$

Assuming you are asking about polynomials only (where exponents are integers from definition) with real coefficients:

expr = 0.2134320980 x^2 + 0.0023432 x + .2 x^3;
(HoldForm[#] &@expr) /. c_Real :> NumberForm[c, {∞, 3}]
0.002 x + 0.213 x^2 + 0.200 x^3

You may use one of the methods introduced here: 20714 to preserve traditional order:

f = HoldForm[+##] & @@ MonomialList@# &;
f[expr] /. c_Real :> NumberForm[c, {∞, 3}]
0.200 x^3 + 0.213 x^2 + 0.002 x
$\endgroup$
2
$\begingroup$
a = 0.2134320980 x^2 + 0.0023432 x;

a /. Times[b_, c_] :> Times[Round[b, 0.0001], c]

0.0023 x + 0.2134 x^2

$\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.