用matlab解方程二分法,matlab 01---解简单方程 方程组 二分法

解简单方程 方程组----matlab

1. **解一元方程;**

2. **解二元一次方程组---inv()**

3. **解二元二次方程---solve vpa**

4. **解一元多次方程---roots()**

5. **用二分法解一元高次方程**

6. **解二元一次方程**

1. 解一元方程;

% x^2-4=12,求x;

syms x;

f=x^2-4-12;

solve(f)

2. 解二元一次方程组—inv()

注:对于 Ax=b;

两种解法:

x=inv(A)*b;

x=A\b; 左除

左除\ 右除/

A\B=inv(A) * B 左除

A/B=A * inv(B) 右除

% x + 2*y = 8

% 2*x + 3*y =13

A=[1,2;2,3];

b=[8;13];

x=inv(A)*b

%或 x=A\b

或:

syms x y;

[x y]=solve(x+2*y==8,2*x+3*y==13)

3. 解二元二次方程—solve vpa

vpa(); 函数求解

% x^2 + 3*y + 1=0

% y^2 + 4*x + 1=0

syms x y;

[x y]=solve(x^2+3*y+1==0,y^2+4*x+1==0);

x=vpa(x,4)% 4表示4位有效数字

y=vpa(y,4)

%解得四组解

4. 解一元多次方程—roots()

a4*x^4+a3*x^3+a2*x^2+

root([a4 a3 a2 a1 a0]);………………

%example:x^4+3*x^2-4*x+5=0

rts=roots([1 0 3 -4 5]) %即可得出结果

5. 用二分法解一元高次方程

%解一元高次方程 用二分法

%仅限于具有实数根的方程

%input:

%a,b:the left and right value of the interval which the root is in

%f:the function that transform from the equation

%tol:the accuracy of root

%output:

%x:the solution of the equation

%interations:the number of interations which is to solve the equation

clc;

close;

clear;

a=input('请输入根的下限:');%0

b=input('请输入根的上限:');%10

tol=input('请输入根的精度:');%0.1

interations=0;

%f(a)*f(b)<0 只考虑该区间有解的情况

while (b-a)>tol

m=(a+b)/2;

if f(m)==0

break;%此时 m为f(x)的根 跳出while循环 迭代次数为0

end

if f(a)*f(m)>0

a=m;

else

b=m;

end

interations=interations+1;

end

x=(a+b)/2;

disp(['方程的根为:',num2str(x)]);

disp(['迭代次数为:',num2str(interations)]);

function y0=f(x)

y0=x^2-1.23;

end

6. 解二元一次方程

function x=quadratic(a,b,c)

%equation:a*x^2+b*x+c=0

%input:a,b,c

%output:x=[x1,x2],the two solutions of this equation

if a==0&b==0&c==0

%disp(' ') 空一行显示

disp('solution inderminate');%解不确定

elseif a==0&b==0

disp('there is no solution');

elseif a==0

disp('only one root:equation is linear');

disp(' x1 x2');

x1=-c/b;

x2=NaN;

disp([x1 x2]);

elseif b^2<4*a*c

disp('x1,x2 are complx roots');

x1=(-b+sqrt(b^2-4*a*c))/(2*a);

x2=(-b-sqrt(b^2-4*a*c))/(2*a);

disp(' x1 x2');

disp([x1 x2]);

elseif b^2==4*a*c

x1=-b/(2*a);

x2=x1;

disp('equal roots');

disp(' x1 x2');

disp([x1 x2]);

else

x1=(-b+sqrt(b^2-4*a*c))/(2*a);

x2=(-b-sqrt(b^2-4*a*c))/(2*a);

disp(' x1 x2');

disp([x1 x2]);

end

end

%verify

%{

a=0.5;b=2;c=1;

quadratic(a,b,c)

x1 x2

-0.5858 -3.4142

%}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值