Solving set of linear equations in plaintext using sympy - python

I would like to add a functionality to solve systems of linear equations to my python based editor. I am looking for a module that would be able to parse a string such as the one below:
sample_volume=20
final_concentration=0.55
ethanol_concentration=0.96
final_volume = ethanol_vol+sample_volume
final_concentration*final_volume=ethanol_vol*ethanol_concentration
And solve for the values of all variables.
I have implemented a quick and dirty script using sympy that does this, see here for a Jupyter notebook.
I think that this must have been implemented by someone in a more robust way, I would like to avoid reinventing the wheel here.
Does anyone know of any alternative implementation that are more robust (have tests etc)?
Additionally, according to the sympy docs, sympy.solveset should be used instead of sympy.solve.
I cannot make this work with a list of equations as in my example. Can someone proficient in sympy guide me how to use solveset with an equation system such as this.

In [2]: sample_volume=20
...: final_concentration=0.55
...: ethanol_concentration=0.96
...:
In [4]: fv,ev = symbols('fv,ev')
In [5]: expr1 = fv - ev+sample_volume
In [6]: expr2 = final_concentration*fv - ev*ethanol_concentration
In [7]: solve([expr1,expr2], [fv,ev])
Out[7]: {ev: -26.8292682926829, fv: -46.8292682926829}
# I will recommend to use solveset's linear system solver (linsolve)
In [8]: linsolve([expr1,expr2], [fv,ev])
Out[8]: {(-46.8292682926829, -26.8292682926829)}

Related

solve an equation (with max-statement) in python

i am seeking a solution for the following equation in Python.
345-0.25*t = 37.5 * x_a
'with'
t = max(0, 10-x_a)*(20-10) + max(0,25-5*x_a)*(3-4) + max(0,4-0.25*x_a)*(30-12.5)
'x_a = ??'
If there is more than one solution to the problem (I am not even sure, whether this can happen from a mathematical point of view?), I want my code to return a positive(!) value for x_a, that minimizes t.
With my previous knowledge in the Basics of Python, Pandas and NumPy I actually have no clue, how to tackle this problem. Can someone give me a hint?
For Clarification: I inserted some exemplary numbers in the equation to make it easier to gasp the problem. In my final code, there might of course be different numbers for different scenarios. However, in every scenario x_a is the only unknown variable.
Update
I thought about the problem again and came up with the following solution, which yields the same result as the calculations done by Michał Mazur:
import itertools
from sympy import Eq, Symbol, solve
import numpy as np
x_a = Symbol('x_a')
possible_elements = np.array([10-x_a, 25-5*x_a, 4-0.25*x_a])
assumptions = np.array(list(itertools.product([True, False], repeat=3)))
for assumption in assumptions:
x_a = Symbol('x_a')
elements = assumption.astype(int) * possible_elements
t = elements[0]*(20-10) + elements[1]*(3-4) + elements[2]*(30-12.5)
eqn = Eq(300-0.25*t, 40*x_a)
solution = solve(eqn)
if len(solution)>2:
print('Warning! the code may suppress possible solutions')
if len(solution)==1:
solution = solution[0]
if (((float(possible_elements[0].subs(x_a,solution))) > 0) == assumption[0]) &\
(((float(possible_elements[1].subs(x_a,solution))) > 0) == assumption[1]) &\
(((float(possible_elements[2].subs(x_a,solution)))> 0) == assumption[2]):
print('solution:', solution)
Compared to the already suggested approach this may have an little advantage as it does not rely on testing all possible values and therefore can be used for very small as well as very big solutions without taking a lot of time (?). However, it probably only is useful as long as you don't have more complex functions for t (even having for example 5 max(...) statements and therefore (2^5=)32 scenarios to test seems quite cumbersome).
As far as I'm concerned, I just realized that my problem is even more complex as i thought. For my project the calculations needed to derive the value of "t" are pretty entangled and can not be written in just one equation. However it still is a function, that only relies on x_a. So I am still hoping for a Python-Solution similar to the proposed Solver in Excel... or I will stick to the approach of simply testing out all possible numbers.
If you are interested in a solution a bit different than the Python one, then I will give you a hand. Open up your Excel, with Solver extention and plug in
the data you are interested in cheking, as the following:
Into the E2 you plug the command I just have writen, into E4 you plug in
=300-0,25*E2
Into the F4 you plug:
=40*F2
Then you open up your Solver menu
Into the Set Objective you put the variable t, which you want to minimize.
Into Changing Variables you put the a.
Into Constraint Menu you put the equality of E4 and F4 cells.
You check the "Make Unconstarained Variables be non-negative" which will prevent your a variable to go below 0. Your method of computing is strictly non-linear, so you leave this option there.
You click solve. The computed value is presented in the screen.
The python approach I can think of:
minimumval=10100
minxa=10000
eps=0.01
for i in range(100000):
k=i/10000
x_a=k
t = max(0, 10-x_a)*(20-10) + max(0,25-5*x_a)*(3-4) + max(0,4-0.25*x_a)*(30-12.5)
val=abs(300-0.25*t-40*x_a)
if (val<eps):
if t<minimumval:
minimumval=t
minxa=x_a
It isn't direct solution, as in it only controls the error that you make in the equality by eps value. However, it gives solution.

Python sympy module problems

I met some problems when I using sympy to solve mathematical problems, my code is like this,
eq1=Eq(0, -sympy.sqrt(x**2) + sympy.sqrt((x + 4)**2))
sympy.solve(eq1,x)
the answer for this equation ought to be -2, but I got an empty list instead
eq1=Eq(0, -sympy.sqrt(x**2) + sympy.sqrt((x + 4)**2))
sympy.solveset(eq1,x)
this should work
OUTPUT
{-2}
btw sympy got an exelent website that would have given you the answer, along with a very intuitive shell inside the browser https://docs.sympy.org/latest/tutorial/solvers.html
here is what sympy has to say on the matter:
"Please note that there is another function called solve which can also be used to solve equations. The syntax is solve(equations, variables) However, it is recommended to use solveset instead."

Solving equations involving ceilings

I would like to solve the equations of the following type in Python. Please let me know if there are any relevant libraries or methods to solve it. ceil(x) denotes the ceiling function.
ceil(x/7)+3*ceil(x/12) = x
This is just a random example, not sure if there is a solution to this.
I tried looking into Sympy library of Python but I can't find a way to use it for my case.
Any help is appreciated. Thanks!
I tried
from sympy import ceiling
from sympy.solvers import solve
from sympy import Symbol
x = Symbol('x')
print(solve(ceiling(x/7) + 3*ceiling(x/12) - x, x))
which ended up in
No algorithms are implemented to solve equation -x + 3*ceiling(x/12) + ceiling(x/7)
The only thing I can think of right now is a graphical solution.

student t confidence interval in python

I am interested in using python to compute a confidence interval from a student t.
I am using the StudentTCI() function in Mathematica and now need to code the same function in python http://reference.wolfram.com/mathematica/HypothesisTesting/ref/StudentTCI.html
I am not quite sure how to build this function myself, but before I embark on that, is this function in python somewhere? Like numpy? (I haven't used numpy and my advisor advised not using numpy if possible).
What would be the easiest way to solve this problem? Can I copy the source code from the StudentTCI() in numpy (if it exists) into my code as a function definition?
edit: I'm going to need to build the Student TCI using python code (if possible). Installing scipy has turned into a dead end. I am having the same problem everyone else is having, and there is no way I can require Scipy for the code I distribute if it takes this long to set up.
Anyone know how to look at the source code for the algorithm in the scipy version? I'm thinking I'll refactor it into a python definition.
I guess you could use scipy.stats.t and its interval method:
In [1]: from scipy.stats import t
In [2]: t.interval(0.95, 10, loc=1, scale=2) # 95% confidence interval
Out[2]: (-3.4562777039298762, 5.4562777039298762)
In [3]: t.interval(0.99, 10, loc=1, scale=2) # 99% confidence interval
Out[3]: (-5.338545334351676, 7.338545334351676)
Sure, you can make your own function if you like. Let's make it look like in Mathematica:
from scipy.stats import t
def StudentTCI(loc, scale, df, alpha=0.95):
return t.interval(alpha, df, loc, scale)
print StudentTCI(1, 2, 10)
print StudentTCI(1, 2, 10, 0.99)
Result:
(-3.4562777039298762, 5.4562777039298762)
(-5.338545334351676, 7.338545334351676)

differential equations calculating

I need to calculate some phrase as below.
d/dx(sin^2(cos(x)) = 2sin(cos(x))*-sin(x)*cos(cos(x))
it is differential equations calculating.
each phrase can place in d(phrase)/dx.
is this ability in python and if is not, how can I calculate this kind of phrase?
Thanks.
See sympy, a symbolic mathematics library.
As the others have said. Take a look at SymPy. Here is a code snippet to demonstrate the relevant functions.
In [1]: from sympy import *
In [2]: x = Symbol('x')
In [3]: (sin(cos(x))**2).diff(x)
Out[3]: -2⋅sin(x)⋅sin(cos(x))⋅cos(cos(x))

Categories

Resources