-1

I made a basic graph plotter in Java using the mXparser library. Now, it does its job just fine, the only problem is that the program itself takes about 2.5 seconds to draw a basic function, like x^2. Can I somehow optimize the algorithm so that it only takes maybe 1-1.6 seconds? I'll leave the code down below.

package rechner;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.geom.Line2D;
import org.mariuszgromada.math.mxparser.Argument;
import org.mariuszgromada.math.mxparser.Expression;
import org.mariuszgromada.math.mxparser.Function;

import oberflaeche.GUI_Controller;

public class drawFunction {

    
    private static final double STEP_VALUE = 0.01;
    private int width;
    private int height;
    Graphics2D g2;
    GUI_Controller GUI;
    Color cornBlue = new Color(100, 149, 237);
    Font mediumFont = new Font("Times New Roman", Font.ITALIC, 25);
    Font bigFont = new Font("Times New Roman", Font.ITALIC, 50);
    
    public drawFunction(int w, int h, GUI_Controller newGUI) {
        width = w;
        height = h;
        GUI = newGUI;
    }
    
    public void drawFunc(Graphics2D g2) {
        
        int originX = width / 2 - 100;
        int originY = height / 2 + 100;
        for(double x = -13; x <= 17; x += STEP_VALUE) {
            // PROGRAM SHOULD READ THE FUNCTION AND CALCULATE THE Y VALUE
            String function = GUI.getFunction();
            Function A1 = new Function(function);
            // REPLACES THE X IN THE STRING WITH THE INTEGER X THAT HAS A VALUE
            Argument x1 = new Argument("x = " + x);
            Expression E1 = new Expression("f(x)", A1, x1);
            double y = E1.calculate();
            g2.setColor(cornBlue);
            double xPixel = x * 50;
            double yPixel = y * 50;
            Line2D.Double dot = new Line2D.Double(originX + xPixel, originY - yPixel, originX + xPixel + STEP_VALUE, originY - yPixel - STEP_VALUE);
            g2.draw(dot);
        }
    }
    
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197

1 Answers1

1

You have made a few "mistakes" in the approach - basically all the objects (e.g.: Functions, Arguments, Expressions) should be declared before the loop and pre-compiled Otherwise, in each cycle of the for loop, you create many new unnecessary instances. Object creation is heavy as math grammar analysis has to be applied resulting in syntax checking and string tokenization.

The best way is to follow mXparser's Tutorial: https://mathparser.org/mxparser-tutorial/

Leroy Kegan
  • 1,156
  • 10
  • 9