DeepLearner
DeepLearner

Reputation: 95

How to convert GEKKO solutions into a float

I am using GEKKO to solve a system of non-linear differential equations. It is able to solve the equations and give me solutions, however the the solutions seem to be saved in some GEKKO object kind of format called "class 'gekko.gk_operators.GK_Value'".

Is there any way for me to convert this into a float? I need to manipulate these values to find to find their average.

Here is my code

from gekko import GEKKO
DELTA=1
OMEGA=0
GAMMA=1
J=3
m = GEKKO()
SZ1, SZ2, SZ3, SX1, SX2, SX3, SY1, SY2, SY3 = [m.Var(value=0) for i in range(9)]
m.Equations([4*J*(SX2*SY1-SX1*SY2)-GAMMA*(1+SZ1)+2*OMEGA*SY1==0,
         2*J*(-2*SX2*SY1+2*SX1*SY2+2*SX3*SY2-2*SX2*SY3)-GAMMA*(1+SZ2)+2*OMEGA*SY2==0,
         2*J*(-2*SX3*SY2+2*SX2*SY3)-GAMMA*(1+SZ3)+2*OMEGA*SY3==0,
         J*SY2*SZ1-0.5*GAMMA*SX1-DELTA*SY1==0,
         2*J*SY1*SZ2-2*J*SY3*SZ2-0.5*GAMMA*SX2-DELTA*SY2==0,
         J*SY2*SZ3-0.5*GAMMA*SX3-DELTA*SY3==0,
         J*SX2*SZ1+0.5*GAMMA*SY1-DELTA*SX1+2*OMEGA*SZ1==0,
         2*J*SX1*SZ2-2*J*SX3*SZ2+0.5*GAMMA*SY2-DELTA*SX2+2*OMEGA*SZ2==0,
         J*SX2*SZ3+0.5*GAMMA*SY3-DELTA*SX3+2*OMEGA*SZ3==0])
m.solve(disp=True)
print([SZ1.value, SZ2.value, SZ3.value])    
ans=(SZ1.value+SZ2.value+SZ3.value)/3
print(ans)

Is there any was for me to convert SZ1, SZ2 and SZ3 into float values?

Upvotes: 3

Views: 818

Answers (1)

anas17in
anas17in

Reputation: 161

Printing SZ1.value gives output:

[-1.0]

which looks like a python list

Hence your code:

SZ1.value+SZ2.value+SZ3.value

is just concatenating three list. If you want to get the float value, you can use:

SZ1.value[0]

Changing your code to:

ans=(SZ1.value[0]+SZ2.value[0]+SZ3.value[0])/3

should give the desired result.

Reference for GK_Value being a python list: https://github.com/BYU-PRISM/GEKKO/blob/master/gekko/gk_operators.py#L118

Upvotes: 4

Related Questions