Return (cardinality, roots[]) for the real solution set of expr = 0. Cardinality comes from `solveset` (the only API that distinguishes a finite set from a periodic ImageSet); reference roots come from `solve` (more capable for transcendental closed forms) or mpmath for the frontier.
(expr, seeds)
| 191 | |
| 192 | |
| 193 | def classify(expr, seeds): |
| 194 | """Return (cardinality, roots[]) for the real solution set of expr = 0. |
| 195 | |
| 196 | Cardinality comes from `solveset` (the only API that distinguishes a finite |
| 197 | set from a periodic ImageSet); reference roots come from `solve` (more |
| 198 | capable for transcendental closed forms) or mpmath for the frontier. |
| 199 | """ |
| 200 | # Frontier: mpmath-recovered numeric roots (solve has no closed form). |
| 201 | if seeds is not None: |
| 202 | roots = [] |
| 203 | for s0 in seeds: |
| 204 | try: |
| 205 | r = mpmath.findroot(lambda v: complex(expr.subs(x, v)), s0) |
| 206 | if abs(r.imag) < 1e-18: |
| 207 | roots.append(mpmath.nstr(r.real, 24)) |
| 208 | except Exception: |
| 209 | pass |
| 210 | return ("finite", sorted(set(roots), key=float)) |
| 211 | |
| 212 | try: |
| 213 | sol = solveset(expr, x, domain=S.Reals) |
| 214 | except Exception: |
| 215 | sol = None |
| 216 | |
| 217 | if sol is S.EmptySet: |
| 218 | return ("empty", []) |
| 219 | # Periodic infinite real solution set (trig): completeness is N/A. |
| 220 | if sol is not None and (sol.has(sp.ImageSet) or "ImageSet" in type(sol).__name__): |
| 221 | return ("infinite", []) |
| 222 | |
| 223 | # Finite set, or a ConditionSet solveset couldn't close — reference roots |
| 224 | # from the capable solver. |
| 225 | roots = solve_real_roots(expr) |
| 226 | if isinstance(sol, FiniteSet): |
| 227 | if not roots: |
| 228 | roots = real_numeric_roots(list(sol)) |
| 229 | return ("finite", roots) |
| 230 | if roots: # ConditionSet but solve() found a finite real closed form |
| 231 | return ("finite", roots) |
| 232 | return ("unknown", []) |
| 233 | |
| 234 | |
| 235 | def sympy_solve(expr): |
no test coverage detected