Solving Simultaneous Equations with Python

I own a very old fashion scientific calculator and it can’t solve any simultaneous equations like those new calculators (not even 2×2!). The situation goes worst when I try to do my Circuit Theory tutorial, in which I need to solve many simultaneous equations. Can’t I just concentrate on forming the equations and let someone to solve them for me?

Well! Let the Python do it!

All you have to do is forming the proper equations. Then, fire up the following script. Key in the proper coefficients of each equation when Python asks.

Please feel free to copy and use it anywhere you like.

Screenshot

#!/bin/python
import numpy as np

print 'How many variables ?'
print '>> ',
total_variable = int(raw_input())

# User key in all the variable numbers

equation_list = []

for i in range(total_variable):
    print
    print 'Please enter the coefficients of the #%d equation.' % (i+1)
    print 'For example: (1)*x0 + (2)*x1 = (3) ---> "1 2 3"'
    print '>> ',
    user_input = raw_input()
    user_token_str = user_input.split()
    assert (len(user_token_str)== (total_variable +1))
    user_token = [float(u) for u in user_token_str]
    equation_list.append(user_token)
print

equation_arr = np.array(equation_list)

#
# A * X = Y
# Given A and Y, we need to find X.
#

Y_arr = equation_arr[:, -1:]
A_arr = equation_arr[:, :-1]

print 'Y_arr:' , Y_arr
print 'A_arr:' , A_arr

X_arr = np.linalg.solve(A_arr, Y_arr)

print 'Answer:'
for i, x in enumerate (X_arr):
    print 'x%d value: %f' % (i, x)
Advertisements

Lorenz Attractor

My salutation to Edward Lorenz, the founder of Chaos Theory. These graphs are generated through Python and SciPy. Try dumping the following codes into the IPython and have fun changing the view of the Lorenz attactor.

Lorenz attractor.
Lorenz attractor.
Lorenz attractor.
Lorenz attractor – YZ view.
Lorenz attractor.
Lorenz attractor – side view.

The following is my Python source code.
Continue reading “Lorenz Attractor”