【发布时间】:2020-05-27 10:02:54
【问题描述】:
我正在尝试做一些软件考古。尝试用 python 中的现代脚本替换旧的 pascal 文件。
在某些时候,pascal 脚本使用如下例程:
FUNCTION zbrent(x1,x2,tol: real;fx:Func): real;
(* in the range x1 to x2, ZBRENT searches for a zero point of fx(x:real):real
until a accuracy of tol is reached. fx must change sign in [x1,x2].
fx must be defined with the far call option on $F+, and not be nested *)
LABEL 99;
CONST
itmax=100;
eps=3.0e-8;
VAR
a,b,c,d,e: real;
min1,min2,min: real;
fa,fb,fc,p,q,r: real;
s,tol1,xm: real;
iter: integer;
BEGIN
a := x1;
b := x2;
fa := fx(a);
fb := fx(b);
IF (fb*fa > 0.0) THEN BEGIN
GotoXY(EelX,EelY+8);
writeln('pause in routine ZBRENT');
write('Root must be bracketed');
Readln;
GotoXY(EelX,EelY+8);
Writeln(' ');
Write(' ');
Goto 99;
END;
fc := fb;
FOR iter := 1 to itmax DO BEGIN
IF (fb/abs(fb)*fc > 0.0) THEN BEGIN
c := a;
fc := fa;
d := b-a;
e := d
END;
IF (abs(fc) < abs(fb)) THEN BEGIN
a := b;
b := c;
c := a;
fa := fb;
fb := fc;
fc := fa
END;
tol1 := 2.0*eps*abs(b)+0.5*tol;
xm := 0.5*(c-b);
IF ((abs(xm) <= tol1) OR (fb = 0.0)) THEN BEGIN
zbrent := b; GOTO 99 END;
IF ((abs(e) >= tol1) AND (abs(fa) > abs(fb))) THEN BEGIN
s := fb/fa;
IF (a = c) THEN BEGIN
p := 2.0*xm*s;
q := 1.0-s
END ELSE BEGIN
q := fa/fc;
r := fb/fc;
p := s*(2.0*xm*q*(q-r)-(b-a)*(r-1.0));
q := (q-1.0)*(r-1.0)*(s-1.0)
END;
IF (p > 0.0) THEN q := -q;
p := abs(p);
min1 := 3.0*xm*q-abs(tol1*q);
min2 := abs(e*q);
IF (min1 < min2) THEN min := min1 ELSE min := min2;
IF (2.0*p < min) THEN BEGIN
e := d;
d := p/q
END ELSE BEGIN
d := xm;
e := d
END
END ELSE BEGIN
d := xm;
e := d
END;
a := b;
fa := fb;
IF (abs(d) > tol1) THEN BEGIN
b := b+d
END ELSE BEGIN
IF (xm > 0) THEN BEGIN
b := b+abs(tol1)
END ELSE BEGIN
b := b-abs(tol1)
END
END;
fb := fx(b)
END;
writeln('pause in routine ZBRENT');
writeln('maximum number of iterations exceeded'); readln;
zbrent := b;
99: END;
在this book, on page 285.中有描述,是Van Wijngaarden-Dekker-Brent方法。
我想用 python 中的一行替换它,最好使用 scipy。我看到有scipy.optimize.brentq method,但有一个巨大的不同:
- Pascal 的 zbrent 仅使用一个容差输入 (tol),而 python 具有 rtol 和 xtol。我不明白它们是什么意思。
该怎么办?我应该在我的 python 程序中给出什么作为 xtol 和 rtol 以使其等效于帕斯卡?我对数值计算一无所知。我很害怕。我只是一个材料科学家!
【问题讨论】:
标签: python scipy numerical-methods