Left overs#
Least Squares#
from scipy.optimize import least_squares
# Define the matrix A and vector b
A = matrix([[1, 2], [3, 4], [5, 6]])
b = vector([7, 8, 9])
# Define a function representing the residual (the function to minimize)
def residual(x):
return A * vector(x) - b
# Initial guess for the solution
x0 = [0, 0] # You can adjust this according to your problem
# Compute the least squares solution
result = least_squares(residual, x0)
print("Least squares solution:", result.x)
Least squares solution: [-6. 6.5]
Note: This example isn’t using core SageMath libraries, instead it is uses scipy.
Distance#
from math import sqrt
# Define the vectors
v1 = vector([1, 2, 3])
v2 = vector([4, 5, 6])
# Calculate the squared differences
squared_diff = sum((v1[i] - v2[i])**2 for i in range(len(v1)))
# Calculate the distance
distance = sqrt(squared_diff)
print("Distance between v1 and v2:", distance)
Distance between v1 and v2: 5.196152422706632
Transpose#
# Define a row vector
row_vector = vector([1, 2, 3])
# Transpose the row vector
transposed_row_vector = matrix([row_vector]).transpose()
print("Original row vector:", row_vector)
print("Transposed row vector:", transposed_row_vector)
# Define a column vector
column_vector = column_matrix([1, 2, 3])
# Transpose the column vector
transposed_column_vector = column_vector.transpose()
print("Original column vector:", column_vector)
print("Transposed column vector:", transposed_column_vector)
Original row vector: (1, 2, 3)
Transposed row vector: [1]
[2]
[3]
Original column vector: [1]
[2]
[3]
Transposed column vector: [1 2 3]