3
$\begingroup$

I have a very large polynomial with Complex Numbers as coefficients. Due to many calculations, there are rounding off errors. I know however by theoretical considerations, that the coefficients are integers and almost all of them give 0. I use Round, Chop to do it but to no avail. Chop for example let me see 1. + 3. x but in reality the internal Reals behind them are 1.00003 or 2.0000002 etc. I must do something wrong. If I do Round[0.00001] everything goes fine. But not if I do Round[0.00001 + 0.00002 x], nothing usefull happens.

$\endgroup$
4
$\begingroup$

eldo already posed and deleted something like this, but I think it works well in many cases:

poly = Expand @ FromDigits[RandomComplex[2 + 2 I, 6], x];

poly /. n_?NumberQ :> Round[n]
(1 + I) + (1 + I) x + I x^2 + (1 + I) x^3 + x^4 + (1 + I) x^5

Note that this will round exponents as well. More robust is the method of rhermans, which might also be written in terms of CoefficientRules:

MapAt[Round, CoefficientRules[poly], {All, 2}] ~FromCoefficientRules~ x
(1 + I) + (1 + I) x + I x^2 + (1 + I) x^3 + x^4 + (1 + I) x^5
$\endgroup$
4
$\begingroup$

You don't give an example so I create my own:

poly = Expand@FromDigits[RandomComplex[2 + 2 I, 6], x]

(0.117797 + 0.674094 I) + (0.980296 + 1.90575 I) x + (0.190167 + 1.68039 I) x^2 + (1.65725 + 1.83193 I) x^3 + (1.07084 + 1.19757 I) x^4 + (0.473445 + 1.37764 I) x^5


Probably you can extract your coefficients first, and then round them

Round @ CoefficientList[poly,x]

{I, 1 + 2 I, 2 I, 2 + 2 I, 1 + I, I}

and then reconstruct the polynomial.

Expand@FromDigits[Reverse[%], x]

I + (1 + 2 I) x + 2 I x^2 + (2 + 2 I) x^3 + (1 + I) x^4 + I x^5


A more general solution would be to have a way to map a function over the coefficients directly

polyMap[f_, poly_, var_] := 
 Expand@FromDigits[
 Reverse[Map[f, CoefficientList[poly, var]]
 ], var]

another data example:

poly2 = Expand@FromDigits[9 RandomComplex[1 + I, 4], x]
(2.92741 +  7.78658 I) + (5.17754 + 3.29475 I) x + (4.93425 +  2.98767 I) x^2 + (6.71465 + 1.91807 I) x^3

Now we map Round over the coefficients

polyMap[Round, poly2, x]

(3 + 8 I) + (5 + 3 I) x + (5 + 3 I) x^2 + (7 + 2 I) x^3

but we could also Map other functions such as Ceiling or Floor

polyMap[Floor, poly2, x]

(2 + 7 I) + (5 + 3 I) x + (4 + 2 I) x^2 + (6 + I) x^3

$\endgroup$
  • $\begingroup$ I'm not sure this is the best way to reconstruct a polynomial from a coefficients list, but it works. Improvements are welcomed. $\endgroup$ – rhermans Sep 17 '14 at 10:54
  • 1
    $\begingroup$ FromDigits seems good but an alternative is to use CoefficientRules. See my answer below. (+1) $\endgroup$ – Mr.Wizard Sep 17 '14 at 11:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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