Solving systems of equations in two variables - Python - python

I just start to learn python and learned about variables, input and basic math.
I been asked to write a mathematical exercise which has the parameters:
ax+by=c, dx+ey=f
a, b, c, d,e, f - the user input and than the program result and write
the answear for x, y
I did:
number1 = float(input('Insert a number1: '))
number2 = float(input('Insert a number2: '))
number3 = float(input('Insert a number3: '))
number4 = float(input('Insert a number4: '))
number5 = float(input('Insert a number:5 '))
number6 = float(input('Insert a number6: '))
I don't how to write an equation with two variables
x=number1+2.5*number2-number3 #(it should be looked like ax+by=c)
y=number5+2.5*number6-number4
ax+by=c AND dx+ey=f ==> x=(-by+ey-f+c)(a-d)
I also don't know why I can't write the variable inside print:
print('the value of x, y is') print((x))

You can write the above equations in matrix form.
You can find answer to (x,y) easily with this method. You just have to solve this matrix equation.
You can find the answer using numpy. (Or you just have to implement matrix inverse and multiplication your own)
import numpy as np
A = np.array([[a, b], [d, e]])
B = np.array([[c], [f]])
print(np.linalg.inv(A) # B)

Well, you must think in a way to solve a equation with 2 variables using a programming language, it's not so straightforward if you're not familiar with programming.
Think about the steps you have to take to solve that manually first and then try to implement that using Python, I'll try to help you with some guiding:
1- Find a number to multiply one of the equations so that you can "remove" one of the variables.
2- Sum both of the equations (forget about the variables for now, work only with their coefficients)
3- After summing both equations and storing the "new_coefficient" values and assuming you removed x you should have something like: ((e*step_1_number)+b)*y = f*step_1_number + c
4- With the previous step you'll be able to find your y value, after that it's pretty easy to find the x value.
I managed to do this using Python but I don't think it's going to be useful for you if I just post my code, try to work something out yourself, good luck!

Related

How do I set 2 expressions equal to eachother and solve for x [duplicate]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Let's say I have an equation:
2x + 6 = 12
With algebra we can see that x = 3. How can I make a program in Python that can solve for x? I'm new to programming, and I looked at eval() and exec() but I can't figure out how to make them do what I want. I do not want to use external libraries (e.g. SAGE), I want to do this in just plain Python.
How about SymPy? Their solver looks like what you need. Have a look at their source code if you want to build the library yourself…
There are two ways to approach this problem: numerically and symbolically.
To solve it numerically, you have to first encode it as a "runnable" function - stick a value in, get a value out. For example,
def my_function(x):
return 2*x + 6
It is quite possible to parse a string to automatically create such a function; say you parse 2x + 6 into a list, [6, 2] (where the list index corresponds to the power of x - so 6*x^0 + 2*x^1). Then:
def makePoly(arr):
def fn(x):
return sum(c*x**p for p,c in enumerate(arr))
return fn
my_func = makePoly([6, 2])
my_func(3) # returns 12
You then need another function which repeatedly plugs an x-value into your function, looks at the difference between the result and what it wants to find, and tweaks its x-value to (hopefully) minimize the difference.
def dx(fn, x, delta=0.001):
return (fn(x+delta) - fn(x))/delta
def solve(fn, value, x=0.5, maxtries=1000, maxerr=0.00001):
for tries in xrange(maxtries):
err = fn(x) - value
if abs(err) < maxerr:
return x
slope = dx(fn, x)
x -= err/slope
raise ValueError('no solution found')
There are lots of potential problems here - finding a good starting x-value, assuming that the function actually has a solution (ie there are no real-valued answers to x^2 + 2 = 0), hitting the limits of computational accuracy, etc. But in this case, the error minimization function is suitable and we get a good result:
solve(my_func, 16) # returns (x =) 5.000000000000496
Note that this solution is not absolutely, exactly correct. If you need it to be perfect, or if you want to try solving families of equations analytically, you have to turn to a more complicated beast: a symbolic solver.
A symbolic solver, like Mathematica or Maple, is an expert system with a lot of built-in rules ("knowledge") about algebra, calculus, etc; it "knows" that the derivative of sin is cos, that the derivative of kx^p is kpx^(p-1), and so on. When you give it an equation, it tries to find a path, a set of rule-applications, from where it is (the equation) to where you want to be (the simplest possible form of the equation, which is hopefully the solution).
Your example equation is quite simple; a symbolic solution might look like:
=> LHS([6, 2]) RHS([16])
# rule: pull all coefficients into LHS
LHS, RHS = [lh-rh for lh,rh in izip_longest(LHS, RHS, 0)], [0]
=> LHS([-10,2]) RHS([0])
# rule: solve first-degree poly
if RHS==[0] and len(LHS)==2:
LHS, RHS = [0,1], [-LHS[0]/LHS[1]]
=> LHS([0,1]) RHS([5])
and there is your solution: x = 5.
I hope this gives the flavor of the idea; the details of implementation (finding a good, complete set of rules and deciding when each rule should be applied) can easily consume many man-years of effort.
Python may be good, but it isn't God...
There are a few different ways to solve equations. SymPy has already been mentioned, if you're looking for analytic solutions.
If you're happy to just have a numerical solution, Numpy has a few routines that can help. If you're just interested in solutions to polynomials, numpy.roots will work. Specifically for the case you mentioned:
>>> import numpy
>>> numpy.roots([2,-6])
array([3.0])
For more complicated expressions, have a look at scipy.fsolve.
Either way, you can't escape using a library.
If you only want to solve the extremely limited set of equations mx + c = y for positive integer m, c, y, then this will do:
import re
def solve_linear_equation ( equ ):
"""
Given an input string of the format "3x+2=6", solves for x.
The format must be as shown - no whitespace, no decimal numbers,
no negative numbers.
"""
match = re.match(r"(\d+)x\+(\d+)=(\d+)", equ)
m, c, y = match.groups()
m, c, y = float(m), float(c), float(y) # Convert from strings to numbers
x = (y-c)/m
print ("x = %f" % x)
Some tests:
>>> solve_linear_equation("2x+4=12")
x = 4.000000
>>> solve_linear_equation("123x+456=789")
x = 2.707317
>>>
If you want to recognise and solve arbitrary equations, like sin(x) + e^(i*pi*x) = 1, then you will need to implement some kind of symbolic maths engine, similar to maxima, Mathematica, MATLAB's solve() or Symbolic Toolbox, etc. As a novice, this is beyond your ken.
Use a different tool. Something like Wolfram Alpha, Maple, R, Octave, Matlab or any other algebra software package.
As a beginner you should probably not attempt to solve such a non-trivial problem.

Finding coefficients of x in a string

I am trying to make an algebra solver, so I have to find the coefficients of x in an expression. Currently this is the code I have to take an input:
equation = input("Enter equation: ")
LHS, RHS = equation.split("=")[0], equation.split("=")[1]
##Remove whitespaces
LHS, RHS = LHS.replace(" ",""), RHS.replace(" ","")
Now I want to get the coefficients of x in the expressions LHS and RHS, how can I do this?
And also, the coefficients may not be just numbers but they may be of the form (2*3+4)x. I think this can be done using the eval() function but I don't know how to apply it.
Note: I want to do this with plain python, without using any modules which are not built-in.
In case it's only one variable and thus only one coefficient you could divide the respective variable/site by x.
Taking your example:
(2*3+4)x
dividing by x gives us the coefficient:
(2*3.4)
If that's not the approach you want to take, you could also convert the expression into a string and exclude "x", as such:
coefficientLHS = LHS.replace("x", "")
However, you should use this cautious as you might have algebra expressions in front of your variable, so regex implementation would be advisable.
Another approach would be to use the module Poly:
x = symbols("x")
coefLHS = Poly(LHS, x)
coefLHS.coeffs()

Python how to get function formula given it's inputs and results

Assume we have a function with unknown formula, given few inputs and results of this function, how can we get the function's formula.
For example we have inputs x and y and result r in format (x,y,r)
[ (2,4,8) , (3,6,18) ]
And the desired function can be
f(x,y) = x * y
As you post the question, the problem is too generic. If you want to find any formula mapping the given inputs to the given result, there are simply too many possible formulas. In order to make sense of this, you need to somehow restrict the set of functions to consider. For example you could say that you're only interested in polynomial solutions, i.e. where
r = sum a_ij * x^i * y^j for i from 0 to n and j from 0 to n - i
then you have a system of equations, with the a_ij as parameters to solve for. The higher the degree n the more such parameters you'd have to find, so the more input-output combinations you'd need to know. Variations of this use rational functions (so you divide by another polynomial), or allow some trigonometric functions, or something like that.
If your setup were particularly easy, you'd have just linear equations, i.e. r = a*x + b*y + c. As you can see, even that has three parameters a,b,c so you can't uniquely find all three of them just given the two inputs you provided in your question. And even then the result would not be the r = x*y you were aiming for, since that's technically of degree 2.
If you want to point out that r = x*y is a particularly simple formula, and you would like to look for simple formulas, then one approach would be enumerating formulas in order of increasing complexity. But if you do this without parameters (since ugly parameters will make a simple formula like a*x + b*y + c appear complex), then it's hard to guilde this enumeration towards the one you want, so you'd really have to enumerate all possible formulas, which will become infeasible very quickly.

Building dict combinations to match a target sum in Python

I have a dict made of N integer values like this:
units = {'trooper':2, 'tank':10, 'helicopter':12}
And I also have a target value... say 120.
I am trying to find all possible results of the equation:
a*units['trooper'] + b*units['tank'] + c*units['helicopter'] = 120
So the result would look something like:
60*trooper
55*trooper + 1*tank
54*trooper + 1*helicopter
And so on with all possible combinations of the N keys in the dict...
How can I go about building this ?
Searching for solutions to these kinds of problems is easiest if you know what they are called. Google for Diophantine equations.
In the Python world, you can use the Sympy package which includes a Diophantine equation solver. That package makes short work of your problem:
from sympy import symbols
from sympy.solvers.diophantine import diop_solve
trooper, tank, helicopter = symbols('trooper tank helicopter', integer=True)
print diop_solve(2*trooper + 10*tank + 12*helicopter - 120)
It outputs:
(5*t - trooper + 60, -6*t + trooper - 60, trooper)
You can also search for "ways to make change" which is another way of expressing the problem. A related problem is called called The Knapsack Problem and it is famously difficult to solve. The math behind solving general systems of linear Diophantine equations is a bit involved. Here are some resources:
http://www.math.udel.edu/~lazebnik/papers/dior1.pdf
http://www.dcc.fc.up.pt/~apt/onlinepapers/epia97_final.pdf
https://en.wikipedia.org/wiki/Diophantine_equation#System_of_linear_Diophantine_equations
http://www.math.utah.edu/~carlson/hsp2004/PythonShortCourse.pdf
Something like this would work for small values of target value:
units = {'trooper':2, 'tank':10, 'helicopter':12}
total = 120
for i in range(int(total/units['helicopter'])):
for j in range(int(total/units['tank'])):
if (total-units['helicopter']*i-units['tank']*j)%2==0 and (total-units['helicopter']*i-units['tank']*j)>0:
print ((total-units['helicopter']*i-units['tank']*j)/2,j,i)

solve equations using multiple values of x

I need help on the fallowing: Lets say you ask the user for an ecuation it can be anything, for illustrating this example lets the the user choose this one:
x**5+3, and he also needs to assign any value of x, so it will look like this:
write the equation:
write the value of x you want to calculate:
my question is: how can you modify the x in the equation the user gave first to assign the value he wants to calculate?? in other worlds how can I make python calculate x**5+2, for x= any input value??
It looks like you want the user to enter an equation with variables and the value for the variable. And you want your code to evaluate the user input equation with user input value for the variable in the equation. Sounds like a candidate for eval():
In [185]: equation = 'x ** 5 + 2'
In [186]: x = 3
In [187]: eval(equation)
Out[187]: 245
Another example:
In [188]: equation = '(x + 99) * 2'
In [189]: x = 1
In [190]: eval(equation)
Out[190]: 200
Since in the above demonstration, equation is a string, it might as well be a user input. When you ask the user to input for the equation, store it in a variable (variable equation here). Then when you ask them for a value for the variables in the equation, cast it to int and just do a eval(equation) in your code.
Your question is hard to decipher, but if I understand correctly, you're talking about writing a function. Try the following:
def f(x):
return x**5 + 2
And you may use the function for any value of x, e.g., f(2).
This is relativity easily to do if you look up each piece of the puzzle (or coding problem in this case).
First you need user input:
x_string = input("Enter an x value: ")
Then you need to convert the input String into an integer:
x = int(x_string)
Finally you need to calculate the value and print it out:
results = x**5 + 2
print results
You seem to be new to Python, so I highly recommend looking up some tutorials (like this one).

Categories

Resources