不动点迭代
function xc = fpi( g, x0, tol )
x(1) = x0;
i = 1;
while 1
x(i + 1) = g(x(i));
if(abs(x(i+1) - x(i)) < tol)
break
end
i = i + 1;
end
xc = x(i+1);
end
牛顿法找根:
$$ f( x ) = ( 1 - \frac{3}{4x} ) ^ {\frac{1}{3} }$$
封装函数计算:x_right = solve('(1 - 3 / (4 * x)) ^ (1 / 3)')
牛顿法实现:
function [y, dirv_y] = funNewton(x)
y = (1 - 3 / (4 * x)) ^ (1 / 3);
dirv_y = (1 - 3 / (4 * x)) ^ (- 2 / 3) / (4 * x ^ 2);
% dirv_y is y's diff
end
clear all
clc
Error = 1e-6;
format long
x_right = solve('(1 - 3 / (4 * x)) ^ (1 / 3)')
%disp the right answer
x = 0.7;
for k = 1:50
[y, dirv_y] = funNewton(x);
%call the function to get the f(x) and it's diff
xk = x;
disp(['the ', num2str(k), ' time is ', num2str(x)])
%xk to save the last time value of x
x = x - y / dirv_y;
%newton solve
if(abs(xk - x) < Error)
%decide whether to break out
break;
end
end
xk
%output the value of x
割线法:
function xc = CutLine( f, x0, x1, tol )
x(1) = x0;
x(2) = x1;
i = 2;
while 1
x(i + 1) = x(i) - (f(x(i)) * (x(i) - x(i - 1))) / (f(x(i)) - f(x(i - 1)));
if(abs(x(i + 1) - x(i)) < tol)
break;
end
i = i + 1;
end
xc = x(i + 1);
end
Stewart平台运动学问题求解:
function out = Stewart( theta )
% set the parameter
x1 = 4;
x2 = 0;
y2 = 4;
L1 = 2;
L2 = sqrt(2);
L3 = sqrt(2);
gamma = pi / 2;
p1 = sqrt(5);
p2 = sqrt(5);
p3 = sqrt(5);
% calculate the answer
A2 = L3 * cos(theta) - x1;
B2 = L3 * sin(theta);
A3 = L2 * cos(theta + gamma) - x2;
B3 = L2 * sin(theta + gamma) - y2;
N1 = B3 * (p2 ^ 2 - p1 ^ 2 - A2 ^ 2 - B2 ^ 2) - B2 * (p3 ^ 2 - p1 ^ 2 - A3 ^ 2 - B3 ^ 2);
N2 = -A3 * (p2 ^ 2 - p1 ^ 2 - A2 ^ 2 - B2 ^ 2) + A2 * (p3 ^ 2 - p1 ^ 2 - A3 ^ 2 - B3 ^ 2);
D = 2 * (A2 * B3 - B2 * A3);
out = N1 ^ 2 + N2 ^ 2 - p1 ^ 2 * D ^ 2;
end
test our function at theta = - pi / 4 and theta = pi / 4
clear all
clc
format short
disp('f(- pi / 4) is ')
out1 = Stewart(- pi / 4)
disp('--------------')
disp('f(pi / 4) is ')
out2 = Stewart(pi / 4)