m.k.l
m.k.l

Reputation: 41

Solving systems of equations in two variables - 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))

Upvotes: 3

Views: 12676

Answers (2)

Ramesh-X
Ramesh-X

Reputation: 5085

You can write the above equations in matrix form.

writing in matrix form

You can find answer to (x,y) easily with this method. You just have to solve this matrix equation.

solution to x and y

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)

Upvotes: 6

Gabriel Belini
Gabriel Belini

Reputation: 779

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!

Upvotes: 0

Related Questions