In: Computer Science
Write a Python program tat asks the user for the number of equations (n) to be solved and fill the coefficient matrix A and the right matrix b with random integers. Limit the values of the elements of A to numbers between 0 and 50 and elements of b to 0 and 500. Lastly, put the matrices into an Excel file.
Python 3 code
import random #imported python inbuilt library for generation random numbers
import xlsxwriter #library for writing in excel file
n=int(input("Enter the number of equation: "))
#As we dont know the number of variables to be solved so we consider n equations with n different varibles
#So to solve n quations with n varible we use quation Ax=B where A is matrix of n*n and x is a varible matrix with n unknown varibles of n*1 an B is right matrix with solution variables of n*1.
#For generating matrix A with random variables between 0 to 50 of n*n
A=[[random.randint(0,50) for i in range(n)] for j in range(n)] #using random function and for loops
x=[f'x{k}' for k in range(n)] #generation of variable matrix
B=[random.randint(0,500) for l in range(n)] #generation of right matrix B
# Workbook() takes one, non-optional, argument
# which is the filename that we want to create.
workbook = xlsxwriter.Workbook(f'result{n}.xlsx')
# The workbook object is then used to add new
# worksheet via the add_worksheet() method.
worksheet = workbook.add_worksheet()
# Start from the first cell. Rows and
# columns are zero indexed.
# Iterate over the data and write it out row by row.
for row in range(n):
for col in range(n):
worksheet.write(row, col, A[row][col])
for rowv in range(n):
worksheet.write(rowv,n,x[row])
for rowb in range(n):
worksheet.write(rowb,n+1,B[rowb])
# Finally, close the Excel file
# via the close() method.
workbook.close()