从Maple到C++的翻译
Translation from Maple to C++
嘿,所以我有一个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);
相关文章:
- 不同翻译单元中不可重载的非内联函数定义
- 需要将一行代码从C++ Qt翻译成PyQt
- 为什么未命名的结构内联变量在每个翻译单元中没有相同的地址?
- 在没有 API 的情况下使用谷歌翻译文本
- 如何执行 cppcheck 交叉翻译单元 (CTU) 静态分析?
- 模板变量是否允许在多个翻译单元中并有效合并?
- 是否允许类在程序中的不同翻译单元之间具有不同的定义?
- 我怎样才能代替使用新的使用malloc翻译
- 为什么具有静态存储持续时间的同一内联变量在包含在 VS2017 编译的两个翻译单元中时会构造和销毁两次
- 如何将 'in' 关键字从 python 翻译成 c++?
- 为什么不同的翻译单元没有独立和沙盒的内存空间?
- 如何用c语言翻译openssl命令pbkdf2
- 为什么编译器不在同一翻译单元中警告 ODR 违规
- 静态变量在同一个翻译单元中被静态方法使用时是否保证被初始化?
- 如何翻译这个给定代码中的 ::* 运算符和member_fn?
- 来自不同翻译单元的函数会干扰吗?
- 在 opengl 中翻译相机时遇到问题
- 如何平均继续翻译向量
- 如何在C++中的不同翻译单元之间共享枚举的实例
- 在Visual Studio中更新Qt翻译(.ts文件)时出现未指定错误