这就是我目前所做的。
import graph;
unitsize(1cm);
size(300);
struct coefficient{
//----------------
real coefficient[];
//----------------
void operator init(... real[] Coefficient){
for (int i=0;i<Coefficient.length;++i) this.coefficient[i]=Coefficient[i];
}
}
coefficient x=coefficient(1,2,3);
real a[]={2,-3,-3,2}; // a[0]=2, a[1]=-3, a[2]=-3, a[3]=2
real polynomial(real x){
real sum=0;
for (int i=0; i<a.length;++i) sum=sum+a[i]*x^i;
return sum;
}
path p=graph(polynomial,-1,2,n=300);
// become --> path p=graph(polynomial(coefficient(2,-3,-3,2)),-3,4,n=300);
draw(p,red);
dot((1,polynomial(1)),blue);
// become --> dot((1,polynomial(1,coefficient(2,-3,-3,2))),blue);
draw(Label("$x$",align=2S,Relative(0.99)),(-3,0)--(3,0),Arrow);
draw(Label("$y$",align=2E,Relative(0.99)),(0,-3)--(0,3),Arrow);
问题:
我想写一个结构来自动绘制多项式方程。但我对struct
Asymptote 的了解很少。
我能怎么做?
答案1
无耻地窃取https://asymptote.sourceforge.io/gallery/2Dgraphs/legend.asy(顺便一提,https://asymptote.sourceforge.io/有一个很棒的示例库),无需结构:
import graph;
size(8cm,6cm,IgnoreAspect);
typedef real realfcn(real);
realfcn polfunc(real[] coeffs) {
return new real(real x) {
real sum = 0;
for (int i=0; i<coeffs.length; ++i){
sum = sum+coeffs[i]*x^i;
}
return sum;
};
};
real ary[][] = {{2,-3,-3,2},{1,2,3,4},{-2,3,1,0}};
for(int i=0; i<ary.length; ++i){
draw(graph(polfunc(ary[i]),-1,2));
dot((1,polfunc(ary[i])(1)),blue);
}
draw(Label("$x$",align=2S,Relative(0.99)),(-1.1,0)--(2.25,0),Arrow);
draw(Label("$y$",align=2E,Relative(0.99)),(0,-10)--(0,40),Arrow);
输出:
希望这和你的期望相差不远。干杯!