简体   繁体   中英

What is the best approach to plot graphs?

I am working on a graphing calculator application, and of course, the main feature of the application is to display graphs.

Right now, this is how my algorithm of plotting graphs works: I divide the drawing canvas in N intervals (where N is defined the application's settings, default value is about 700). For each interval, I evaluate the function for the two ends, and I draw a segment between the two points.

Here are the disadvantages I found to this method:

  • The precision of the graph isn't great (for example the function sin(tan(x)) )
  • Rendering gets slow for a higher number of intervals (eg N is above 1000). Also, zoom and navigation controls suffer.

So is there a better approach to drawing graphs?

I am programming in C# (WPF), but I think this is irrelevant, because I am looking for an algorithm.

You don't need to write your own algorithm if you are plotting some arbitrary functions. Use a graph control from a relevant library, see here and provide the neccessary data (x, y cordinates).

I hope i can help you with this snippet of C++ program which i made few years back using primitive graphics.h ported for mingw compiler. The variable names are pretty much clear.

void func_gen(char expr[100],float precision,int color)
{
     float x=-(xres/2)/(float)zoom_factor;
     float max_range=-x;
     while(x<=max_range)
     {
        float y;
        y = evalu(expr,x);          //user defined function which i used to evaluate ann expression
        float xcord=xby2+zoom_factor*x+xshift;
        float ycord=yby2-zoom_factor*y+yshift;
        if(xcord<=xres && xcord>=0 && ycord>=0 && ycord<=yres)
            putpixel(xcord,ycord,color);
            x=x+precision;
     }
}

This method gets pretty slow when i reduce the precision value (which actually increases the precision of the plot:p, sorry for noobness)

A better approach would be to use adaptive interval sizes. That is, start with relatively coarse intervals, say 20. For each interval, compute the function for the interval ends and the middle. If the middle point is close to the line connecting the two end points, draw a line and you're done with that interval. If not, split the interval in two and repeat with the two smaller intervals.

If the interval gets too small without converging to a line, you've probably found a discontinuity and should not connect the interval endpoints.

I think you should do with DrawPath . That method use an auxiliary structure (a GraphicsPath ) optimized just for kind of task as you are coding. edit A small optimization could be to eval the function just at the left point of the segment, and eval at close point just on last segment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM