java - 如何将 f(x) 作为用户输入并使其像使用 java 代码的公式一样工作?
问题描述
我是编码新手!如果你觉得这个问题很傻,那么我一开始就请你原谅!我试图用java解决二分法。而我成功地做到了!我将用户输入用于初始猜测 'a' 和 'b'!在我的代码中,我创建了一个存储“f(x) = x^3 - x - 1”的方法,当我调用此方法时,它会按照我给定的说明解决二分法。
- 问题是我想从用户那里获取 f(x) 并像公式一样使用它。
- 我尝试将 f(x) 作为 String 一次,但接下来呢?我怎样才能把它变成一个公式?
- 另一个问题是我不能使用 '^' 符号作为电源,我目前正在使用 Math.pow(x,pow); 有什么方法可以让它('^')作为电源工作吗?
- 如果用户输入“3x^2 - 2x - 6”,我应该如何让程序意识到给定方程表示(假设 x = 4)“3*4^2 - 2*4 - 6”,而不是“ 34^2 - 24 - 6" !
我经历了很多答案,但他们无法满足我!我在下面添加我的程序,如果有人可以检查!
//二分法
package numericalMethods;
import java.util.*;
public class BisectionMethod {
public static void main(String[] args) {
double a, b, c;
Scanner sc = new Scanner(System.in);
System.out.print("Enter value of a : ");
a = sc.nextDouble();
System.out.print("Enter value of b : ");
b = sc.nextDouble();
System.out.print("Enter maximum iteration : ");
c = sc.nextDouble();
System.out.println();
if ((f(a) < 0 && f(b) > 0) || (f(a) > 0 && f(b) < 0)) {
for(int i = 1; i <= c; i++){
System.out.println("*** For iteration " + i + " ***");
System.out.println("a is a = " + a + " and b is b = " + b);
System.out.println("So f(a) is f(a) = " + f(a) + " and " + "f(b) is f(b) = " + f(b));
//declaration and calculation of root variable
double x = (a+b)/2;
System.out.println("For iteration " + i + " root is x = " + x);
System.out.println("And f(x) is f(x) = " + f(x));
System.out.println("Here f(a)*f(x) = " + (f(a) * f(x)) );
//Condition for assignment of the value of root x!
if(f(a)*f(x) < 0){
b = x;
System.out.println("As f(a)*f(x) < 0, we assign value of x to b.");
System.out.println("So now a and b are respectively, a = "+ a + " and b = " + b);
System.out.println();
}else if (f(a)*f(x) >0) {
a = x;
System.out.println("As f(a)*f(x) > 0, we assign value of x to a.");
System.out.println("Now a and b are respectively, a = "+ a + " and b = " + b);
System.out.println();
}
}
}else {
System.out.println("The condition was not fullfilled!");
}
}
//declares function
public static double f(double x){
return ((x*x*x)-x-4);
}
}
解决方案
您可以使用 ScriptEngineManager 使用 javascript 引擎评估数学表达式。
俄亥俄州 你需要先用它的替代品替换“x”:
String formula = "x/2 + x";
Integer X = 6;
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine eng = mgr.getEngineByName("JavaScript");
System.out.println(eng.eval(formula.replace("x", X)));
但是你的问题看起来像“家庭作业”,所以我怀疑这个解决方案是否可以接受。
推荐阅读
- kubernetes - 当在 GCE 中将 externalTrafficPolicy 设置为 Local 时,Kubernetes LoadBalancer 类型服务的外部 IP 无法从集群内的 pod 访问
- python - SQL Alchemy - UndefinedColumn 存在时出错
- javascript - 应用过滤器后,如何更新个人计数?
- java - 如何显示带有注释且没有嵌入字体的 PDF?
- xslt - 使用 XSLT 按节点数将大型 XML 拆分为较小的块
- python-3.x - Jupyterlab 中的 Geopandas (read_file) CRSError 消息
- reactjs - 如何在 React.js 中自定义 Material-UI KeyboardDatePicker 的 ToolbarComponent?
- sql - 将正则表达式查询转换为 SQL Server
- javascript - 如何从 fb messenger chat 访问 [object Promise] 值
- php - php在while循环中选择一个随机数组值并将其分配给一个变量