2

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!

Kuba
  • 136,707
  • 13
  • 279
  • 740
  • If exponents are integers then you can use quick approach: 0.2134320980 x^2 + 0.0023432 x /. r_Real :> Round[r, .001] – Kuba Jun 14 '14 at 20:16
  • works pretty well. can it be also done that it adds zeros if the original number was too short? – the_next_generation Jun 14 '14 at 20:22
  • @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". – eldo Jun 14 '14 at 20:48
  • @ kuba - OK, I have to improve my reading, sorry for that :) – eldo Jun 14 '14 at 20:50

2 Answers2

3

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
Kuba
  • 136,707
  • 13
  • 279
  • 740
2
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

eldo
  • 67,911
  • 5
  • 60
  • 168