Reputation: 636
I have derived some equations with some variables. I want to solve to an unknown variable. I am using Sympy. My code is as follows:
import sympy as syp
import math as m
#this is the unknown variable that I want to find
C0 = syp.Symbol('C0')
#Known variables
D0 = 0.874
theta2 = 10.0
fi2 = 80.0
theta1 = (theta2/180.0)*m.pi
fi1 = (fi2/180.0)*m.pi
#Definitions of 6 different equations all of them in respect to CO.
C_t = 5*m.pi*(D0+4*C0)
St123 = 1.5*theta1*(D0+2*C0)
St45 = fi1*(D0+7*C0)
l1 = syp.sqrt((0.5*(D0+4*C0)-0.5*D0*m.cos(theta1))**2 + (0.5*D0*m.sin(theta1))**2)
l2 = syp.sqrt((0.5*(D0+6*C0)-0.5*(D0+2*C0)*m.cos(theta1))**2 + (0.5*(D0+2*C0)*m.sin(theta1))**2)
l3 = syp.sqrt((0.5*(D0+8*C0)-0.5*(D0+4*C0)*m.cos(theta1))**2 + (0.5*(D0+4*C0)*m.sin(theta1))**2)
#Definition of the general relationship between the above functions. Here C0 is unknown and C_b
C_b = C_t + 6*C0 + 3*(l1+l2+l3) - 3*St123 - 3*St45
#for C_b = 10.4866, find C0
syp.solve(C_b - 10.4866, C0)
As observed, I want to solve the C_b relationship to C0. Until the last line my code works fine. When I ran the whole script it seems that takes ages to calculate the C0. I dont have any warning message but I dont have any solution either. Would anybody suggest an alternative or a possible solution? Thanks a lot in advance.
Upvotes: 0
Views: 1800
Reputation: 6549
As I have mentioned in a comment this problem is numerical in nature, so it is better to try to solve it with numpy/scipy. Nonetheless it is an amusing example of how to do numerics in sympy so here is one suggested workflow.
First of all, if it was not for the relative complexity of the expressions here, scipy would have been definitely the better option over sympy. But the expression is rather complicated, so we can first simplify it in sympy
and only then feed it to scipy
:
>>> C_b
38.0∗C0
+3.0∗((0.17∗C0+0.076)∗∗2+(2.0∗C0+0.0066)∗∗2)∗∗0.5
+3.0∗((0.35∗C0+0.076)∗∗2+(2.0∗C0+0.0066)∗∗2)∗∗0.5
+3.0∗((2.0∗C0+0.0066)∗∗2+0.0058)∗∗0.5
+9.4
>>> simplify(C_b)
38.0∗C0
+3.0∗(4.0∗C0∗∗2+0.027∗C0+0.0058)∗∗0.5
+3.0∗(4.1∗C0∗∗2+0.053∗C0+0.0058)∗∗0.5
+3.0∗(4.2∗C0∗∗2+0.08∗C0+0.0058)∗∗0.5
+9.4
Now given that you are not interested in symbolics and that the simplification was not that good, it would be useless to continue using sympy instead of scipy, but if you insist you can do it.
>>> nsolve(C_b - 10.4866, C0, 1) # for numerical solution
0.00970963412692139
If you try to use solve
instead of nsolve
you will just waste a lot of resources in searching for a symbolic solution (that may not even exist in elementary terms) when a numeric one is instantaneous.
Upvotes: 1