Consider a polynomial such as:
p = [1 -9 27 -27];
obviously the real root is 3:
polyval(p,3)
0
While using the roots
function
q = roots([1 -9 27 -27]);
with format short
:
q =
3.0000 + 0.0000i
3.0000 + 0.0000i
3.0000 - 0.0000i
and to check if the the roots are real:
bsxfun(@eq,ones(size(q)),isreal(q))
0
0
0
And even worse with format long
I get:
roots([1 -9 27 -27])
ans =
3.000019414068325 + 0.000000000000000i
2.999990292965843 + 0.000016813349886i
2.999990292965843 - 0.000016813349886i
How can I calculate roots of a polynomial correctly?
You can find the roots, or solutions, of the polynomial equation P(x) = 0 by setting each factor equal to 0 and solving for x. Solve the polynomial equation by factoring. Set each factor equal to 0.
Finding one root If f is a polynomial, the computation is faster when using Horner's method or evaluation with preprocessing for computing the polynomial and its derivative in each iteration.
We can find the Roots or Zeros of a polynomial by setting the polynomial equal to 0 and factoring.
Description. r = roots( p ) returns the roots of the polynomial represented by p as a column vector. Input p is a vector containing n+1 polynomial coefficients, starting with the coefficient of xn.
You may have to work symbolically. You need the Symbolic Math Toolbox for that.
Define the polynomial as a symbolic function. You can (a) use poly2sym
to generate the symbolic polynomial from its coefficients. Or (b) better yet, define the symbolic function directly using a string. That way you avoid the loss of accuracy that may result from representing the coefficients as double
.
Use solve
, which symbolically solves algebraic equations.
Code with option (a):
p = [1 -9 27 -27];
ps = poly2sym(p);
rs = solve(ps);
Code with option (b):
ps = sym('x^3-9*x^2+27*x-27');
rs = solve(ps);
In either case, the result is symbolic:
>> rs
rs =
3
3
3
You may want to convert to numeric values using
r = double(rs);
In your example, this gives
>> format long
>> r
r =
3
3
3
This is due to floating point inaccuracies. Have a look at this post for details: Is floating point math broken?
One thing you can do is to round off the answer/s upto some decimal places like this:
q = round(roots([1 -9 27 -27]), 4) % rounding off to 4 decimal places
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With