Skip to content

Commit 93b3b14

Browse files
committed
First implementation of least squares
1 parent 8070e6f commit 93b3b14

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
Class {
2+
#name : #PMLeastSquares,
3+
#superclass : #Object,
4+
#category : #'Math-Numerical'
5+
}
6+
7+
{ #category : #'as yet unclassified' }
8+
PMLeastSquares >> solveMatrixA: aPMMatrix vectorB: aPMVector [
9+
10+
"SVD-based implementation of a minimum-norm solution to the overdetermined least squares problem.
11+
minimize || b - Ax ||"
12+
13+
| svd u s v pseudoinverse |
14+
svd := PMSingularValueDecomposition decompose: aPMMatrix.
15+
16+
u := svd leftSingularMatrix.
17+
s := svd diagonalSingularValueMatrix.
18+
v := svd rightSingularMatrix.
19+
20+
pseudoinverse := s inverse.
21+
22+
^ v * pseudoinverse * u transpose * aPMVector
23+
]
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
"
2+
A PMLeastSquaresTest is a test class for testing the behavior of PMLeastSquares
3+
"
4+
Class {
5+
#name : #PMLeastSquaresTest,
6+
#superclass : #TestCase,
7+
#instVars : [
8+
'matrixA',
9+
'vectorB',
10+
'expectedSolution'
11+
],
12+
#category : #'Math-Tests-Numerical'
13+
}
14+
15+
{ #category : #running }
16+
PMLeastSquaresTest >> setUp [
17+
super setUp.
18+
19+
"Put here a common initialization logic for tests"
20+
21+
matrixA := PMMatrix rows: #(
22+
(0 1.1)
23+
(1 0)
24+
(0 -0.2)).
25+
26+
vectorB := #(1.1 -1.1 -0.2) asPMVector.
27+
expectedSolution := #(-1.1 1) asPMVector.
28+
]
29+
30+
{ #category : #tests }
31+
PMLeastSquaresTest >> testSolve [
32+
33+
| leastSquares solution |
34+
leastSquares := PMLeastSquares new.
35+
36+
solution := leastSquares solveMatrixA: matrixA vectorB: vectorB.
37+
38+
self assert: solution closeTo: expectedSolution.
39+
]

0 commit comments

Comments
 (0)