Search code examples
pythonsympynumber-formatting

Numeric value of solve result in sympy


I tried to calculate the numeric values of the result of the solve function. In WolframAlpha it is called "Approximate forms".

This are my equations:

>>> solve([Eq(u, r * i), Eq(p, u * i), Eq(p, 20), Eq(r, 4)])
[{i: -√5, p: 20, r: 4, u: -4⋅√5}, {i: √5, p: 20, r: 4, u: 4⋅√5}]

I tried N, but it does not seem to work:

>>> N(solve([Eq(u, r * i), Eq(p, u * i), Eq(p, 20), Eq(r, 4)]), 2)
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/base/data/home/apps/s~sympy-live-hrd/66.426491309333028408/sympy/sympy/core/evalf.py", line 1544, in N
    return sympify(x, rational=True).evalf(n, **options)
AttributeError: 'list' object has no attribute 'evalf'

What is the right syntax to do this?


Solution

  • The N function can only be applied to sympy expressions, not lists or dicts. You can use list/dict comprehensions to rebuild the solution data structure like this:

    In [22]: [{k: N(e) for k, e in s.items()} for s in sol]
    Out[22]: [{i: -2.23606797749979, p: 20.0, r: 4.0, u: -8.94427190999916}, {i: 2.23606797749979, p: 20.0, r: 4.0, u: 8.94427190999916}]