yomath
yomath

Reputation: 23

Sympy solveset store results as float, integer etc

I am solving cumulative probability functions (or equations in general if you want to think about it this way) with sympy solveset. So far so good. They return however "sets" as a type of result output. I am having troubles converting those to or saving those as standard python variable types: In my case I would like it to be a float.

My code is as follows:

import sympy as sp
from sympy import Symbol 
from sympy import erf
from sympy import log
from sympy import sqrt

x = Symbol('x')   
p = 0.1

sp.solveset((0.5 + 0.5*erf((log(x) - mu)/(sqrt(2)*sigma)))-p)
Out[91]: 
FiniteSet(7335.64225447845*exp(-1.77553477605362*sqrt(2)))

Is there a possibility to convert this to float? just using float() does not work as I have tried this and I also have gotten so far to somehow store it as a list and then extracting the number again. However this way seems very cumbersome and not suited to my purpose. In the end I will let us say solve this equation above a 1000 times and I would like to have all the results as a neat array containing floating point numbers.

If you store the above result as follows:

q = sp.solveset((0.5 + 0.5*erf((log(x) - mu)/(sqrt(2)*sigma)))-p)

then Python says the type is sets.setsFiniteSet and if you try to access the variable q it gives you an error (working in Spyder btw):

"Spyder was unable to retrieve the value of this variable from the console - The error message was: 'tuple object has no attribute 'raise_error'".

I have no idea what that means. Thanks a lot.

Upvotes: 0

Views: 1663

Answers (1)

Oscar Benjamin
Oscar Benjamin

Reputation: 14480

The FiniteSet works like a Python set. You can convert it to a list and extract the element by indexing e.g.:

In [3]: S = FiniteSet(7335.64225447845*exp(-1.77553477605362*sqrt(2)))                                                                         

In [4]: S                                                                                                                                      
Out[4]: 
⎧                  -1.77553477605362⋅√2⎫
⎨7335.64225447845⋅ℯ                    ⎬
⎩                                      ⎭

In [5]: list(S)                                                                                                                                
Out[5]: 
⎡                  -1.77553477605362⋅√2⎤
⎣7335.64225447845⋅ℯ                    ⎦

In [6]: list(S)[0]                                                                                                                             
Out[6]: 
                  -1.77553477605362⋅√2
7335.64225447845⋅ℯ                    

In [7]: list(S)[0].n()                                                                                                                         
Out[7]: 595.567591563886

Upvotes: 1

Related Questions