-
Notifications
You must be signed in to change notification settings - Fork 2
/
views.py
63 lines (55 loc) · 2.22 KB
/
views.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
from django.shortcuts import render
from .forms import MatrixAForm, MatrixBForm
import numpy as np
def matrix_calculator(request):
result = ''
error = ''
form_a = MatrixAForm(request.POST or None, prefix='a')
form_b = MatrixBForm(request.POST or None, prefix='b')
if form_a.is_valid() and form_b.is_valid():
matrix_a = []
matrix_b = []
for i in range(3):
row_a = []
row_b = []
for j in range(3):
row_a.append(form_a.cleaned_data[f'matrix_a_{i}{j}'])
row_b.append(form_b.cleaned_data.get(f'matrix_b_{i}{j}', 0))
matrix_a.append(row_a)
matrix_b.append(row_b)
matrix_a = np.array(matrix_a)
matrix_b = np.array(matrix_b)
is_matrix_b_provided = not (matrix_b == 0).all()
operation = request.POST.get('operation')
try:
if operation == 'add':
if is_matrix_b_provided:
result = matrix_a + matrix_b
else:
error = 'Matrix B is required for addition.'
elif operation == 'subtract':
if is_matrix_b_provided:
result = matrix_a - matrix_b
else:
error = 'Matrix B is required for subtraction.'
elif operation == 'multiply':
if is_matrix_b_provided:
result = matrix_a @ matrix_b
else:
error = 'Matrix B is required for multiplication.'
elif operation == 'determinant':
result = np.linalg.det(matrix_a)
elif operation == 'eigenvalues':
eigenvalues = np.linalg.eigvals(matrix_a)
result = eigenvalues
elif operation == 'eigenvectors':
_, eigenvectors = np.linalg.eig(matrix_a)
result = eigenvectors
else:
error = 'Invalid operation'
except ValueError as ve:
error = str(ve)
except Exception as e:
error = str(e)
result = str(result)
return render(request, 'matrix_calculator/index.html', {'form_a': form_a, 'form_b': form_b, 'result': result, 'error': error})