2

Problem: I need to solve these equations with Python.

a + 3b + 2c + 2d = 1
2a + b + c + 2d = 0
3a + b + 2c + d = 1
2a + c + 3d = 0

So I can get the value for a, b, c and d. Is there a way that I can show them in a fraction?

My code:

import numpy as np
A = np.array([[1,3,2,2],[2,1,1,2]])
B = np.array([1,0,1,0])
X2 = np.linalg.solve(A,B)

Error:

LinAlgError: Last 2 dimensions of the array must be square
Matt Hall
  • 7,614
  • 1
  • 23
  • 36
  • 'n' variable equation needs 'n' equation to be solved (general rule of math). In your case, you have given only the first 2 equations, but you also need to give the other two equations to solve it. – Joish Nov 02 '19 at 14:42

2 Answers2

4

You didn't add the last two equations of your problem to the A matrix:

import numpy as np
A = np.array([[1,3,2,2],[2,1,1,2],[3,1,2,1],[2,0,1,3]])
B = np.array([1,0,1,0])
X2 = np.linalg.solve(A,B)

Gives:

array([-0.27272727, -0.18181818,  1.09090909, -0.18181818])

This should work.

Matt Hall
  • 7,614
  • 1
  • 23
  • 36
Wavy
  • 188
  • 7
2

How to get fractions with sympy:

import sympy as sp
a,b,c,d = sp.symbols(list("abcd"))

eqns = [a+3*b+2*c+2*d-1,
        2*a+b+c+2*d,
        3*a+b+2*c+d-1,
        2*a+c+3*d]

sp.solve(eqns,a,b,c,d)
# {a: -3/11, b: -2/11, c: 12/11, d: -2/11}
Paul Panzer
  • 51,835
  • 3
  • 54
  • 99