Java中计算数学表达式的方法 [英] Method for evaluating math expressions in Java

查看:24
本文介绍了Java中计算数学表达式的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的一个项目中,我想添加一个用户可以在公式中提供的功能,例如

In one of my projects I want to add a feature where the user can provide in a formula, for example

sin (x + pi)/2 + 1

我在我的 Java 应用程序中使用的

which I use in my Java app

/**
 * The formula provided by the user
 */
private String formula; // = "sin (x + pi)/2 + 1"

/*
 * Evaluates the formula and computes the result by using the
 * given value for x
 */
public double calc(double x) {
    Formula f = new Formula(formula);
    f.setVar("x", x);
    return f.calc();
    // or something similar
}

如何计算数学表达式?

推荐答案

还有一个表达式 exp4j评估器基于 Dijkstra 的调车场.它在 Apache License 2.0 下免费提供和重新分发,大小只有 25KB 左右,并且非常易于使用:

There's also exp4j, an expression evaluator based on Dijkstra's Shunting Yard. It's freely available and redistributable under the Apache License 2.0, only about 25KB in size, and quite easy to use:

Calculable calc = new ExpressionBuilder("3 * sin(y) - 2 / (x - 2)")
        .withVariable("x", varX)
        .withVariable("y", varY)
        .build()
double result1=calc.calculate();

当使用较新的 API 版本(如 0.4.8)时:

When using a newer API version like 0.4.8:

Expression calc = new ExpressionBuilder("3 * sin(y) - 2 / (x - 2)")
    .variable("x", x)
    .variable("y", y)
    .build();
double result1 = calc.evaluate();

还有一个工具可以在 exp4j 中使用自定义函数.

There's also a facility to use custom functions in exp4j.

这篇关于Java中计算数学表达式的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆