不动点迭代法(matlab)

不动点迭代法(matlab),第1张

syms x

eq = input('Enter the equation you want to solve:','s')

f = inline(eq)%将字符串转化为函数,这里使用@(x)亦可

%disp(f)

%eps= input('eps=')

eps=1e-5%为方便起见,这里固定eps,可随时调整

a1=input('inf=')

a2=input('sup=')%输入解的范围

x=input('x=')

x1=1

count=0

while (x1>eps&&count<50)%复数解暂时没考虑到如何处理,简单粗暴地添谨念加了一个迭代次数上限

 梁吵   xb=x

    x=f(x)

    x1=vpa(abs(x-xb),6)

    if(x1>=10)

        break

    end

    count=count+1

end

if(x1>=10)

    disp('该迭代式不收敛')

elseif(x>a2||x<a1)

        disp('在给定区间内找不到合适的解')

else

    disp('符合精度的解为: ')

    fprintf('%.6f',x)

    disp('橡晌侍迭代次数为:')

    disp(count)

end

不动点迭代

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)


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/yw/12525707.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-26
下一篇 2023-05-26

发表评论

登录后才能评论

评论列表(0条)

保存