| f g det2x2 partialDerivative jacobian aN bN newtonMethod x0 y0 h epsilon |
" Функции для вычисления определителя матрицы 2х2 и частной производной "
f := [:x :y | x * x + y * y - 4].
g := [:x :y | x - y].
det2x2 := [:a :b :c :d | a * d - b * c].
partialDerivative := [:func :x :y :h :derivativeType |
derivativeType = 'x'
ifTrue: [(func value: x + h value: y) - (func value: x value: y) / h]
ifFalse: [derivativeType = 'y'
ifTrue: [(func value: x value: y + h) - (func value: x value: y) / h]
ifFalse: [Error signal: 'Invalid derivative type']]].
jacobian := [:func1 :func2 :x :y :h |
det2x2
value: (partialDerivative value: func1 value: x value: y value: h value: 'x')
value: (partialDerivative value: func1 value: x value: y value: h value: 'y')
value: (partialDerivative value: func2 value: x value: y value: h value: 'x')
value: (partialDerivative value: func2 value: x value: y value: h value: 'y')].
aN := [:func1 :func2 :x :y :h |
det2x2
value: (func1 value: x value: y)
value: (partialDerivative value: func1 value: x value: y value: h value: 'y')
value: (func2 value: x value: y)
value: (partialDerivative value: func2 value: x value: y value: h value: 'y')].
bN := [:func1 :func2 :x :y :h |
det2x2
value: (partialDerivative value: func1 value: x value: y value: h value: 'x')
value: (func1 value: x value: y)
value: (partialDerivative value: func2 value: x value: y value: h value: 'x')
value: (func2 value: x value: y)].
" Функция для вычисления метода Ньютона "
newtonMethod := [:func1 :func2 :x0 :y0 :h :epsilon |
| x y continueIteration |
x := x0.
y := y0.
continueIteration := true.
[continueIteration] whileTrue: [
| jacobianValue aNValue bNValue newX newY |
jacobianValue := jacobian value: func1 value: func2 value: x value: y value: h.
aNValue := aN value: func1 value: func2 value: x value: y value: h.
bNValue := bN value: func1 value: func2 value: x value: y value: h.
newX := x - aNValue / jacobianValue.
newY := y - bNValue / jacobianValue.
(newX - x) abs <= epsilon and: [(newY - y) abs <= epsilon] ifTrue: [continueIteration := false] ifFalse: [x := newX. y := newY].
].
^ Array with: x with: y].
" Начальные значения и параметры "
x0 := 1.0.
y0 := 1.0.
h := 1e-6.
epsilon := 1e-10.
" Вычисление метода Ньютона "
| result |
result := newtonMethod value: f value: g value: x0 value: y0 value: h value: epsilon.
Transcript show: 'x = ', result first printString, ', y = ', result second printString.