Forum Archive

help fsolve (numpy)

alexandrepfurlan

Hi all,

I'm trying obtain the roots of a function that depends on a parameter. For example : The equation

   eos= math.log(1.-x)+x**2*(e22*y+ e11*(1-y) + 2*y*(1-y)*e12)

I need to obtain the roots (x) such as eos = 0 for a specific value of y. In order words, I fix y, and I solve (using fsolve) eos. I'm trying to do :

`def EOS(x,y) :
   e11=1.00 ; e22=0.40 ; e12=0.60
   return math.log(1.-x)+x**2*(e22*y+ e11*(1-y) + 2*x2*(1-y)*e12)


for i in arange(1,99,1) :
   y=i*0.01
   ans[i]=fsolve(lambda x: EOS(x,y),x0)

But I have a wrong answer. Someone know how use the fsolve (or other alternative way) with y as parameter (not a variable) ? Someone could help me ?

Many thanks for the help

Best

Alexandre

Webmaster4o

You'll probably have better luck posting on stackoverflow. It's a wider community

dgelessus

The sympy library (preinstalled in Pythonista) might be useful for this, it allows you to work with formulas and equations that contain symbols, and I think you can substitute symbols and solve for a symbol as a variable and such. I haven't used those features of sympy much (I use it mostly as an advanced calculator) so I can't help you with any details, sorry.

ccc

This podcast might be of interest for a recent description of Sympy from its author. https://forum.omz-software.com/topic/2694/has-anyone-ever-hacked-with-sympy

JonB

alex, pythonista does not, as far as i can tell, come with fsolve.

perhaps you can elaborate about what is failing. If you plug your answer back into EOS, does it return something near zero? If so, you have found your root. If not, is it possible that a real root does not exist?

What are you using for x0, and x2 in the code you posted? One problem you may be having: x=0 is a root of your above equation for all y, and in fact is the only root unless x2 is less than -0.8333. Perhaps this is nit the function you meant to be finding roots of (missing parenthesis, etc?)

It might help you to plot these functions vs x.

import matplotlib.pyplot as plt
import numpy as np
x2=-1 #roots only exist if x2 is negative, and <-0.83

def EOS(x,y) :
   e11=1.00 ; e22=0.40 ; e12=0.60
   return np.log(1.-x)+x**2*(e22*y+ e11*(1-y) + 2*x2*(1-y)*e12)

for i in np.arange(1,99,1) :
   y=i*0.01
   #ans[i]=fsolve(lambda x: EOS(x,y),x0)
   x=np.linspace(-5,1,100)
   plt.plot(x,EOS(x,y))
plt.show()