Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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!

share|improve this question
    
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 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 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 at 20:48
    
@ kuba - OK, I have to improve my reading, sorry for that :) –  eldo Jun 14 at 20:50

2 Answers 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

share|improve this answer

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
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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