Computing partial derivatives of functions in Java

I need to calculate the first derivative of a user-defined function. The program reads the function as a string from a file, and then calculates the derivative with respect to one variable. A function has more variables and can be linear or non-linear. What is the easiest way to do this? Could MATLAB (possibly) be possible or something else?

PS The program does not have access to the Internet.

+3
source share
3 answers

You can use a symbolic algebra library such as javacalculus .

import java.util.Scanner;
import javacalculus.core.CALC;
import javacalculus.core.CalcParser;
import javacalculus.evaluator.CalcSUB;
import javacalculus.struct.CalcDouble;
import javacalculus.struct.CalcObject;
import javacalculus.struct.CalcSymbol;

public class Demo
{
    public static void main(String[] args) throws Exception
    {
        Scanner in = new Scanner(System.in);

        System.out.println("Enter expression:");
        String expression = in.nextLine();
        // javacalculus uses uppercase function names
        expression = expression.replace("sin", "SIN");
        expression = expression.replace("cos", "COS");

        System.out.println("Differentiate with respect to:");
        String variable = in.nextLine();

        // differentiate
        String command = "DIFF(" + expression + ", " + variable + ")";
        CalcParser parser = new CalcParser();
        CalcObject parsed = parser.parse(command);
        CalcObject result = parsed.evaluate();

        // compute numerical value
        result = subst(result, "a1", 0.0);
        result = subst(result, "a2", 10.0);
        result = CALC.SYM_EVAL(result);

        System.out.println("Result:");
        System.out.println(result);
    }

    static CalcObject subst(CalcObject input, String var, double number)
    {
        CalcSymbol symbol = new CalcSymbol(var);
        CalcDouble value = new CalcDouble(number);
        return CalcSUB.numericSubstitute(input, symbol, value);
    }
}

Example input and output:

Enter the expression: To
sin(a1) * 4 * a2 + (a1 + 1)^2
differentiate with respect to:
a1
Result:
42

+3
source

, , :) ( , ), . CalcObject, .

    CalcObject result = parsed.evaluate();

    // compute numerical value
    result = subst(result, "a1", 0.0);
    result = subst(result, "a2", 10.0);
    result = CALC.SYM_EVAL(result);

subst (..)

    CalcSymbol symbol = new CalcSymbol(var);
    CalcDouble value = new CalcDouble(number);
    return CalcSUB.numericSubstitute(input, symbol, value);

CalcObeject subst(...), . ? CalcObject.

- ?

. , , Tom . , . , .

, , . a (a1+a2+a3)*q a1+a2+a3, q. , , , .:)

, . - , .

0

I'm a little late, but.

If I want to inform you about MathParseKit. https://github.com/B3rn475/MathParseKit

This is a C ++ library that can be used to analyze and solve functions.

Among all the functions you can get a variable function.

0
source

All Articles