Andres Valdez
Andres Valdez

Reputation: 164

Non- negative and float solutions needed

I am trying to solve a simple algebra problem, the solutions can be real, and complex.

I am looking there only the positive and real solutions, in this case I have written the following example:

Mostly I have tried to ask python for every member in the answer list the "type(ans) is float and after ask if its positive".

    res = sp.solve(self.dflux * (self.u - u_0) - (self.flux - flux_0), self.u)

        for it in res:
            print(it)
            if(type(it) is float):
                print('here')

    print(type(res),res)

for example in the following case

<class 'list'> [-0.707106781186548, 0.0, 0.707106781186548]

I see no "here" at all.

the same happens for the next case

<class 'list'> [0.0, 0.793216505472184, -0.398143686499772 - 0.949955974569196*I, -0.398143686499772 + 0.949955974569196*I, 0.603391747263908 - 2.16302515309992*I, 0.603391747263908 + 2.16302515309992*I]

I was expecting to see here 3 times for the first example, and two times for the second one, but nothing.

New part:

I have slightly changed the script for the following version:

    for it in res:
        print(it)
        print(isinstance(it,float),type(it))
        if(isinstance(it,float) == True):
            print('here')

The output i see for the first case, is the next:

-0.707106781186548
 False <class 'sympy.core.numbers.Float'>

 0.0
 False <class 'sympy.core.numbers.Float'>

 0.707106781186548
 False <class 'sympy.core.numbers.Float'>

 <class 'list'> [-0.707106781186548, 0.0, 0.707106781186548]

Really strange for me this behavior. In one hand pythons says is not a float but in the other hand it says it is...

Upvotes: 0

Views: 258

Answers (2)

developer_hatch
developer_hatch

Reputation: 16224

In python there is a function for that:

isinstance(0.56, float)



>> true

Edit

there is no need to do if(expresion == True), you just can do if(expresion)

In your case, your float is not python float, is sympy float, so you just have to do:

import sympy

isinstance(sympy.Float(0.56),sympy.Float)
for it in res:
    if(isinstance(it,sympy.Floa)):
        print('here')

Upvotes: 0

G. Anderson
G. Anderson

Reputation: 5955

This appears to be a quirk of SymPy, where a sumpy Float != a python float. (Note the capitalization)

Observe:

import sympy

x=float(16)
x
16.0

isinstance(x,float)
True

y=sympy.Float(x)
y
16.0000000000000

type(y)
sympy.core.numbers.Float

isinstance(y,float)
False

isinstance(y,sympy.Float)
True

So I would say the solution to the type-checking is in the last line, sympy.Float

Upvotes: 2

Related Questions