2

This is what I do so far.

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);

Question:

I want to write a struct to plot polynomial equations automatically. But my knowledge about struct in Asymptote is very little.

How can I do?

0

1 Answer 1

1
+200

Shamelessly stolen from https://asymptote.sourceforge.io/gallery/2Dgraphs/legend.asy (by the way, https://asymptote.sourceforge.io/ has got a great gallery of examples), with no need for struct:

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);

Output:

screenshot

Hope that's not too far away from what you wanted. Cheers!

0

You must log in to answer this question.