gpt4 book ai didi

java - 从 .txt 文件中读取方程式并将其设置为方法的返回

转载 作者:行者123 更新时间:2023-12-01 07:57:47 25 4
gpt4 key购买 nike

我正在尝试使用牛顿正切法求解给定的方程。正切法的工作原理是假设解位于给定 a 和 b 的 a-b 区间内的某个位置,并且函数在 [a,b] 区间上连续。我已经编写了该程序并且运行良好,但现在我必须为其制作一个 GUI,并且必须从文本文件中读取方程。我的问题是我不知道如何从 .t​​xt 文件中获取方程并将其设置为我的函数方法的返回。这应该适用于任何给定的方程。下面是我的方程代码:x^3 -4 * x^2 + 5 * x^1 -12

这是代码:

static double f(double x) { // the function from the .txt file
//return Math.pow(x, 3) - 4* Math.pow(x,2) + 5 * Math.pow(x, 1) - 12;
return x * x * x - 4 * x * x + 5 * x - 12;
}

static double df(double x) { // the function derivative
return 3 * x * x - 8 * x + 5;
}

static String metTangent() {
double b = 4, c, reduceIntervalBy, precision = 0.00000000001;
// reduceIntervalBy holds the value of how much should the interval be reduced by, starting from b to a, so from right to left
DecimalFormat decimalformat = new DecimalFormat("#.00000000000000");

do {
c = b - f(b) / df(b);
//System.out.println(c);
reduceIntervalBy = b - c;
b = c;
} while (reduceIntervalBy > precision );
return "The solution is: " + decimalformat .format(c);
}

解决了。谢谢大家的帮助:)

最佳答案

您可以使用以下方法从文本文件中读取方程。

 static  String getEquation () throws Exception
{
Scanner in = new Scanner(new FileReader("C:\\test1.txt"));
StringBuffer br = new StringBuffer();

while(in.hasNext())
{
br.append(in.next());
}
return br.toString();
}

然后将方程和要计算的值解析为以下函数。

static Object f(double x,String eq) throws Exception {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
engine.put("x",x);
return engine.eval(eq);
}

关于java - 从 .txt 文件中读取方程式并将其设置为方法的返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27979250/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com