简体   繁体   中英

Finding basis of affine space in python?

Suppose I am given an affine space as some conjunction of equalities say:

x + y + z = 2 && x - 3z = 4

which I represent in python as:

[ [1,1,1,2] , [1,0,-3,4] ]

I would like to find the basis of this affine set. Does python have any such library?

Little bit of mathematics :

Let the affine space be given by the matrix equation Ax = b. Let the k vectors {x_1, x_2, .. x_k } be the basis of the nullspace of A ie the space represented by Ax = 0. Let y be any particular solution of Ax = b. Then the basis of the affine space represented by Ax = b is given by the (k+1) vectors {y, y + x_1, y + x_2, .. y + x_k }. If there is no particular solution for Ax = b, then return some error message, as the set represented is empty.

For the above equation the matrix equation is:

Ax = b where

A = [[1, 1, 1], [1, 0, -3]]

x = [x, y, z]^T

b = [2, 4]^T

If you are looking for a numerical (ie approximate) solution then you can try this:

import numpy as np
import scipy

A = np.array([[1,1,1] , [1,0,-3]])
b = np.array([2, 4])

null_sp = scipy.linalg.null_space(A)
x0 = np.linalg.lstsq(A, b, rcond=None)[0][..., None]
aff_basis = np.c_[np.zeros(A.shape[1])[..., None], x] + x0
print(aff_basis) 

It gives:

[[ 1.69230769  1.10395929]
 [ 1.07692308  1.86138762]
 [-0.76923077 -0.9653469 ]]

You find two points on the line by adding two constraints and solving for the remaining unknowns:

x = 1 -> (1, 2, -1)
z = 0 -> (4, -2, 0)

This requires the resolution of two easy 2x2 systems, no need for a library.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM