Stoppt die Vorratsdatenspeicherung! Jetzt klicken &handeln! Willst du auch an der Aktion teilnehmen? Hier findest du alle relevanten Infos
und Materialien:

17.11.2009 mathematischer Funktions-Parser mit BeanShell

Oft kommt man in Projekten in die Verlegenheit, Benutzer-definierte mathematische Funktionen zu berechnen, z.B. für einen Funktionsplotter. Solches lässt sich ohne große Umstände mit BeanShell erledigen:

import bsh.*;

/// Calculates y=f(x) with x, y € double
public class Function {

    Interpreter interpreter = new Interpreter();
    {
        try {
            interpreter.eval(
                    // add some shortcuts for math functions
                    "sin(a) { return Math.sin(a); } \n" +
                    "cos(a) { return Math.cos(a); } \n" +
                    "tan(a) { return Math.tan(a); } \n" +
                    "atan(a) { return Math.atan(a); } \n" );
        } catch (Exception e) {
            // this can not happen in production code
            e.printStackTrace();
        }
    }   

    private String function;

    /// example: new Function("sin(x)+cos(x/3)/2")
    public Function(String function) {
        this.function = function;
    }   

    /// calculates y=f(x) using the function from the constructor
    double y(double x) throws EvalError {
        interpreter.set("x", x);
        interpreter.eval("y=" + function);
        return (Double) interpreter.get("y");
    }   

    /// example which prints y=f(x)=atan(x) from x in 0...9
    public static void main(String[] args) throws EvalError {

        Function f = new Function("atan(x)");

        for ( double x = 0; x < 10; ++x ) {
            System.out.println("f("+x+") = " + f.y(x) );
        }       

    }   

}

In Maven2-basierten Build-Umgebungen kann BeanShell direkt aus einem Repository eingebunden werden, z.B. (auf aktuelle Version achten):

<dependency>
    <groupId>org.apache.maven</groupId>
    <artifactId>maven-script-beanshell</artifactId>
    <version>2.2.1</version>
</dependency>

VN:F [1.9.7_1111]
Rating: 5.0/5 (4 votes cast)
mathematischer Funktions-Parser mit BeanShell, 5.0 out of 5 based on 4 ratings