dxy logo
首页丁香园病例库全部版块
搜索
登录

【原创】octave中| 和 || 的用法

发布于 2014-03-07 · 浏览 1299 · IP 浙江浙江
这个帖子发布于 11 年零 93 天前,其中的信息可能已发生改变或有所发展。
最近在学习chapra的Applied Numerical Methods with MATLAB for Engineers and Scientists,在octave下运行bisect.m,代码如下:
function [root,fx,ea,iter]=bisect(func,xl,xu,es,maxit,varargin)
% bisect: root location zeroes
% [root,fx,ea,iter]=bisect(func,xl,xu,es,maxit,p1,p2,...):
% uses bisection method to find the root of func
% input:
% func = name of function
% xl, xu = lower and upper guesses
% es = desired relative error (default = 0.0001%)
% maxit = maximum allowable iterations (default = 50)
% p1,p2,... = additional parameters used by func
% output:
% root = real root
% fx = function value at root
% ea = approximate relative error (%)
% iter = number of iterations
if nargin<3,error('at least 3 input arguments required'),end
test = func(xl,varargin{:})*func(xu,varargin{:});
if test>0,error('no sign change'),end
if nargin<4|isempty(es), es=0.0001;end
if nargin<5|isempty(maxit), maxit=50;end
iter = 0; xr = xl; ea = 100;
while (1)
xrold = xr;
xr = (xl + xu)/2;
iter = iter + 1;
if xr ~= 0,ea = abs((xr - xrold)/xr) * 100;end
test = func(xl,varargin{:})*func(xr,varargin{:});
if test < 0
xu = xr;
elseif test > 0
xl = xr;
else
ea = 0;
end
if ea <= es | iter >= maxit,break,end
end
root = xr; fx = func(xr, varargin{:});
在命令行窗口输入:>> f=@(x) x*x-3*x+1;>> bisect(f,-10,10)
出现如下代码错误:
warning: C:\Users\USER\AppData\Local\Temp\360zip$Temp\360$0\bisect.m: possible Ma
tlab-style short-circuit operator at line 19, column 12
warning: C:\Users\USER\AppData\Local\Temp\360zip$Temp\360$0\bisect.m: possible Ma
tlab-style short-circuit operator at line 20, column 12
warning: C:\Users\USER\AppData\Local\Temp\360zip$Temp\360$0\bisect.m: possible Ma
tlab-style short-circuit operator at line 35, column 15
error: no sign change
error: called from:
error: C:\Users\USER\AppData\Local\Temp\360zip$Temp\360$0\bisect.m at line 18,
column 11
如果将19,20,35行的| 改成||后,运行正确。
google了octave和matlab的文档,发现如下文字:
MATLAB has special behavior that allows the operators ‘&’ and‘|’ to short-circuit when used in the truth expression for if and while statements. The Octave parser may be instructed to behave in thesame manner, but its use is strongly discouraged.
由此可见,在octave中&和|是没有short circuit操作的。




















































最后编辑于 2022-10-09 · 浏览 1299

2 收藏点赞

全部讨论0

默认最新
avatar
2
分享帖子
share-weibo分享到微博
share-weibo分享到微信
认证
返回顶部