欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Matlab牛顿迭代法求方程的根(GUI)

程序员文章站 2022-06-07 09:51:35
...

牛顿迭代法的具体内容不赘述
它的核心算法是:

k = 1;
x = x0;
x0 = x + e*2; % 为了让初启动时满足循环条件
while (abs(x-x0))>e && (k<=N)  % 同时限定误差和最大循环次数
    x0 = x;
    x = x0 - f(x0)/df(x0);  % 牛顿迭代法式子
    k = k+1;
end

这是一个非常简单的牛顿法实现,根据上学期学的数值分析和这学期上的Matlab,把它用GUI简单包装了一下。

Matlab牛顿迭代法求方程的根(GUI)
用户输入函数表达式、初值、最大容许误差、最大循环次数之后,就可以计算根。代码实现如下。

function varargout = Newton_TEST(varargin)
% NEWTON_TEST MATLAB code for Newton_TEST.fig
%      NEWTON_TEST, by itself, creates a new NEWTON_TEST or raises the existing
%      singleton*.
%
%      H = NEWTON_TEST returns the handle to a new NEWTON_TEST or the handle to
%      the existing singleton*.
%
%      NEWTON_TEST('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in NEWTON_TEST.M with the given input arguments.
%
%      NEWTON_TEST('Property','Value',...) creates a new NEWTON_TEST or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before Newton_TEST_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to Newton_TEST_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help Newton_TEST

% Last Modified by GUIDE v2.5 12-Mar-2020 23:03:08

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @Newton_TEST_OpeningFcn, ...
                   'gui_OutputFcn',  @Newton_TEST_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


% --- Executes just before Newton_TEST is made visible.
function Newton_TEST_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to Newton_TEST (see VARARGIN)
handles.FUN = [];
handles.X0 = [];

% Choose default command line output for Newton_TEST
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes Newton_TEST wait for user response (see UIRESUME)
% uiwait(handles.figure1);


% --- Outputs from this function are returned to the command line.
function varargout = Newton_TEST_OutputFcn(hObject, eventdata, handles) 
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;



function editFUN_Callback(hObject, eventdata, handles)
% hObject    handle to editFUN (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of editFUN as text
%        str2double(get(hObject,'String')) returns contents of editFUN as a double
handles.FUN = get(hObject,'String');
guidata(hObject, handles);


% --- Executes during object creation, after setting all properties.
function editFUN_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editFUN (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function editX0_Callback(hObject, eventdata, handles)
% hObject    handle to editX0 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of editX0 as text
%        str2double(get(hObject,'String')) returns contents of editX0 as a double
handles.X0 = str2num(get(hObject,'String'));
guidata(hObject, handles);


% --- Executes during object creation, after setting all properties.
function editX0_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editX0 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function editError_Callback(hObject, eventdata, handles)
% hObject    handle to editError (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of editError as text
%        str2double(get(hObject,'String')) returns contents of editError as a double
handles.ERROR = str2num(get(hObject,'String'));
guidata(hObject, handles);

% --- Executes during object creation, after setting all properties.
function editError_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editError (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function editN_Callback(hObject, eventdata, handles)
% hObject    handle to editN (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of editN as text
%        str2double(get(hObject,'String')) returns contents of editN as a double
handles.N = str2num(get(hObject,'String'));
guidata(hObject, handles);

% --- Executes during object creation, after setting all properties.
function editN_CreateFcn(hObject, eventdata, handles)
% hObject    handle to editN (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on selection change in listboxK.
function listboxK_Callback(hObject, eventdata, handles)
% hObject    handle to listboxK (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns listboxK contents as cell array
%        contents{get(hObject,'Value')} returns selected item from listboxK


% --- Executes during object creation, after setting all properties.
function listboxK_CreateFcn(hObject, eventdata, handles)
% hObject    handle to listboxK (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: listbox controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on selection change in listboxX.
function listboxX_Callback(hObject, eventdata, handles)
% hObject    handle to listboxX (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns listboxX contents as cell array
%        contents{get(hObject,'Value')} returns selected item from listboxX


% --- Executes during object creation, after setting all properties.
function listboxX_CreateFcn(hObject, eventdata, handles)
% hObject    handle to listboxX (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: listbox controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in pushbuttonRUN.
function pushbuttonRUN_Callback(hObject, eventdata, handles)
% hObject    handle to pushbuttonRUN (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
cla
f = handles.FUN;
x0 = handles.X0;
N = handles.N;
e = handles.ERROR;

f = eval(['@(x)',f]); % 将用户输入的str类型转化为有意义的匿名函数
df = eval(['@(x)',char(diff(sym(f)))]); % 计算微分

node = line(x0,f(x0),'Marker','o','MarkerSize',8,'MarkerFaceColor','r','MarkerEdgeColor','r');
connectline = line(x0,f(x0),'linewidth',1,'color','b'); %用来画连接的线

k = 1;
x = x0;
x0 = x+e*2;
K = [];
X = [];
xcon = x0;
ycon = f(x0);

while (abs(x-x0))>e && (k<=N)
    x0 = x;
    x = x0 - f(x0)/df(x0);
    xcon = [xcon,x];  % 用将新的x值同旧值连接
    ycon = [ycon,f(x)];
    K = [{num2str(k)};K];
    X = [{num2str(x)};X];
    
    % 将循环结果呈现在界面
    set(handles.listboxK,'string',K);
    set(handles.listboxX,'string',X);
    set(node,'xdata',x,'ydata',f(x));
    set(connectline,'xdata',xcon,'ydata',ycon);
    pause(0.5)  % 为了能让人眼看到过程,用pause暂停0.5s
    
    k = k+1; 
end

hold on
xline = sort(xcon);
[xx,yy] = fplot(f,[min(xline),max(xline)]);  %画出模拟曲线
plot(xx,yy,'--k');

用一个的高次方程举例是这样
Matlab牛顿迭代法求方程的根(GUI)

纯纯纯纯小白,发上来是希望可以互相交流,以及督促自己继续联系其他的数值方法。

相关标签: 数值分析