sympy.count_roots: type mismatch when working with real polynomial
<p>I am using sympy and trying to compute number of roots of a polynomial</p>

<pre><code>from sympy.abc import x
from sympy import Poly
p = Poly(x**4+0.1,x)
</code></pre>

<p>At this point, p is polynomial with domain 'RR': <code>Poly(1.0*x**4 + 0.1, x, domain='RR')</code></p>

<p>If I try to compute number of roots in the interval, I get:</p>

<pre><code>p.count_roots(0,2)
TypeError: unsupported operand type(s) for *=: 'RealElement' and 'PythonRational'
</code></pre>

<p>However, if I define</p>

<pre><code>q = Poly(x**3-1, x)
ans: Poly(x**3 - 1, x, domain='ZZ')

q.count_roots(0,2)
ans: 1
</code></pre>

<p>Similarly, if I ask for number of roots of <code>p</code> on the whole domain, that works as well</p>

<pre><code>p.count_roots()
ans: 1
</code></pre>

<p>What should I do to supply correct types to count_roots?    </p>

<p>When possible, use exact (instead of floating point) numbers in your symbolic expressions (this principle is true for all symbolic math software, not only sympy). </p>

<p>In this case, the constant term <code>0.1</code> in the definition of <code>p</code> can be replaced by the (exact) ratio representation <code>1/10</code>. Sympy uses <code>Rational</code> to describe ratios of numbers (since, an input <code>1/10</code> is interpreted by python as a floating point division and automatically transformed to <code>0.1</code>). </p>

<p>The following code works.</p>

<pre><code>from sympy.abc import x
from sympy import Poly, Rational
p = Poly( x**4 + Rational(1,10), x)
p.count_roots(0,2)
</code></pre>

<blockquote>
  <p><code>0</code></p>
</blockquote>

<p>See also <code>sympy.nsimplify</code> for transforming arbitrary floating point numbers such as, e.g., <code>12.21525</code>, to (approximately equal) rationals.</p>

python sympy symbolic-math polynomial-math