从Maple到C++的翻译

Translation from Maple to C++

本文关键字:翻译 C++ Maple      更新时间:2023-10-16

嘿,所以我有一个maple程序,它做平分法,我必须把它转换成C++。我试着根据maple论坛上的代码生成帮助进行转换,但它一直在抛出错误。我希望在这方面能得到一些帮助。谢谢,

这是枫木的代码


使用平分法解决以下数学问题:a.方程的最小正根

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

Δ=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.6enb=%+9.6f   %+12.6enn",a,u,b,v); e:=b-a; if (sign(u)<>sign(v)) then   printf(" n       x            fn");   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.6en",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.6en",0.5*(a+b),evalf(subs(x=0.5*(a+b),feq))); fi: end: with(plots):

警告,更名coords已被重新定义

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

如果将feq保留为过程,则不需要subs调用。

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.6enb=%+9.6f   %+12.6enn",a,u,b,v);
  e:=b-a;
  if (sign(u)<>sign(v)) then
    printf(" n       x            fn");
    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.6en",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.6en",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);

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

例如,我也可以通过以下方式创建过程f。(请注意,其中一个生成的C代码中Pi的默认10位数近似值,另一个生成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);