1

嘿,所以我有一个执行二分法的枫树程序,我必须将它转换为 C++。我尝试根据枫叶论坛上的代码生成帮助所说的进行转换,但它一直抛出错误。我会很感激这方面的一些帮助。谢谢,

这是枫树的代码


使用二分法求解下列数学问题: a.方程的最小正根

f(x):=evalf(1/x-evalf(Pi)*cos(evalf(Pi)*x));

delta = 10^-5 和 eps = 10^-6

plot(f(x),x=.05..10.0);

从上图中我们可以得出结论,给定方程的最小正实根位于 0.0 和 2.0 之间

为了获得所需的准确值,我们调用具有根隔离间隔 (0.01,2.0) 的二分法:

Bisect:=proc(funct_equation,ai,bi,Mi,epsfi,deltaxi) local k,M,a,b,u,v,w,c,e,epsf,deltax,feq, notsolved: M:=Mi: feq:=funct_equation: a:=ai: b:=bi: epsf:=epsfi: deltax:=deltaxi: notsolved:=true: u:=evalf(subs(x=a,feq)): v:=evalf(subs(x=b,feq)): printf("a=%+9.6f   %+12.6e\nb=%+9.6f   %+12.6e\n\n",a,u,b,v); e:=b-a; if (sign(u)<>sign(v)) then   printf(" n       x            f\n");   for k from 1 by 1 while (k<M and notsolved) do:
    e:=0.5*e;
    c:=a+e;
    w:=evalf(subs(x=c,feq)):
    printf("%2d  %+9.6f    %+12.6e\n",k,c,w);
    if (abs(e)<deltax or abs(w)<epsf) then
      notsolved:=false:
    else
      if (sign(w) <> sign(u)) then
        b:=c: v:=w:
      else
        a:=c: u:=w:
      fi:
    fi:    od:    printf("Root = %+9.6f  function = %+12.6e\n",0.5*(a+b),evalf(subs(x=0.5*(a+b),feq))); fi: end: with(plots):

警告,名称更改坐标已重新定义

Bisect(f(x),0.01,2.0,30,1.0e-6,1.0e-5):
4

1 回答 1

1

如果你把你的作为一个程序,你就不需要那个subs电话了。feq

restart:
Bisect:=proc(func::procedure,ai,bi,Mi,epsfi,deltaxi)
local k::integer,
  M::integer,
  a,b,u,v,
  w::float,
  c,e,
  epsf::float,
  deltax,
  notsolved;
  M:=Mi:
  a:=ai: b:=bi: epsf:=epsfi:
  deltax:=deltaxi: notsolved:=true:
  u:=func(a);
  v:=func(b);
  printf("a=%+9.6f   %+12.6e\nb=%+9.6f   %+12.6e\n\n",a,u,b,v);
  e:=b-a;
  if (sign(u)<>sign(v)) then
    printf(" n       x            f\n");
    for k from 1 by 1 while (k<M and notsolved) do
      e:=0.5*e;
      c:=a+e;
      w:=func(c);
      printf("%2d  %+9.6f    %+12.6e\n",k,c,w);
      if (abs(e)<deltax or abs(w)<epsf) then
        notsolved:=false:
      else
       if (sign(w) <> sign(u)) then
         b:=c: v:=w:
       else
         a:=c: u:=w:
       fi:
     fi:
   od:
   printf("Root = %+9.6f  function = %+12.6e\n",0.5*(a+b),func(0.5*(a+b),feq));
 fi:
 0.5*(a+b);
end:

with(plots):

f:=subs(Pi=evalf[16](Pi),proc(x::float) 1/x-Pi*cos(Pi*x); end proc);

Bisect(f,0.01,2.0,30,1.0e-6,1.0e-5);

f(%);

CodeGeneration[C](f);

CodeGeneration[C](Bisect);

此外,如果您从表达式 for 开始,您始终可以使用该命令f将其转换为运算符(一种过程,但也可以由代码生成) 。unapply

例如,我还可以f通过以下方式创建过程。(请注意,其中一个在生成的 C 代码中生成一个默认的 10 位近似值 Pi,另一个生成一个 16 位近似值。)

f_expression := 1/x-Pi*cos(Pi*x);

f:=unapply(f_expression, [x::float]);

CodeGeneration[C](f);

f:=subs(Pi=evalf[16](Pi),unapply(f_expression, [x::float]));

CodeGeneration[C](f);
于 2011-04-26T20:48:30.970 回答