I'm a Python initiator and I'd like to solve the following problems, but I don't know what the cause is.I approached the problem using 'fsolve' an optimization tool.
First of all, I'm trying to solve a nonlinear equation, but I've approached it in two cases. One case worked out well. But I can't find another case.
First case (complete case)
from sympy import *
from scipy.optimize import fsolve
import numpy as np
y= symbols('y')
b_1, b_2 = symbols ('b_1,b_2')
b = 1
f = b_1 + b_2*(y/b)**2
K1 = integrate(f**2,(y,0,b))
eq1 = diff(K1,b_1)
eq2 = diff(K1,b_2)
def function(v):
b_1 = v[0]
b_2 = v[1]
return (2*b_1 + 2*b_2/3,2*b_1/3 + 2*b_2/5)
x0 = [1,1]
solutions = fsolve(function,x0)
sol = np.zeros(2)
sol[0] = solutions[0]
sol[1] = solutions[1]
sol
Out[413]: array([-5.e-324, 1.e-323])
Second case (Fail case)
from sympy import *
from scipy.optimize import fsolve
import numpy as np
y= symbols('y')
b_1, b_2 = symbols ('b_1,b_2')
b = 1
f = b_1 + b_2*(y/b)**2
K1 = integrate(f**2,(y,0,b))
eq1 = diff(K1,b_1)
eq2 = diff(K1,b_2)
def function(v):
b_1 = v[0]
b_2 = v[1]
return (eq1,eq2)
x0 = [1,1]
solutions = fsolve(function,x0)
sol = np.zeros(2)
sol[0] = solutions[0]
sol[1] = solutions[1]
The message that failed is as follows.
runfile('C:/Users/user/Desktop/******/untitled0.py', wdir='C:/Users/user/Desktop/******')
Traceback (most recent call last):
File "C:\Users\user\AppData\Roaming\Python\Python37\site-packages\sympy\core\expr.py", line 327, in __float__
raise TypeError("can't convert expression to float")
TypeError: can't convert expression to float
Traceback (most recent call last):
File "C:\Users\user\Desktop\*******\untitled0.py", line 29, in <module>
solutions = fsolve(function,x0)
File "C:\Users\user\anaconda3\lib\site-packages\scipy\optimize\minpack.py", line 147, in fsolve
res = _root_hybr(func, x0, args, jac=fprime, **options)
File "C:\Users\user\anaconda3\lib\site-packages\scipy\optimize\minpack.py", line 225, in _root_hybr
ml, mu, epsfcn, factor, diag)
error: Result from function call is not a proper array of floats.
Simply enter mathematical expressions eq1,eq2 directly into the 'Return', But the results is different from manually input the expressions.
I tried many things for converting 'sympy function' into 'float array', but it didn't go well.
I tried 'lambdify','lambda'... These were also failed.
How can i enter a function defined as 'sympy' in the form of float to calculate with the optimization tool 'fsolve'?
Actually, The codes above are not my cases. As it is Just simplified situation. But in my cases it's not possible to manually input all functions like above that because i am going to solve a very complex non-linear equation that has hundreds of terms in the tenth or higher order.
Is there anyone who can solve this problem?
sympy
expression cannot be used reliably innumpy
orscipy
.scipy
solvers require a numpy/python function, not one that uses sympy symbols. If you can't getlambdify
to work, stick with sympy solvers. - hpaulj